import React, { useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import {
  CreditCardIcon, UserIcon, CalendarDaysIcon, BuildingOffice2Icon,
  WrenchScrewdriverIcon, BanknotesIcon, UsersIcon, ShieldCheckIcon,
  TagIcon, ChatBubbleLeftRightIcon, UserCircleIcon, MagnifyingGlassIcon,
} from '@heroicons/react/24/outline';

// ── Settings menu configuration ─────────────────────────────────────────────
// Single source of truth for the settings sub-navigation (desktop shell +
// mobile list). `to` = an existing admin route; items without `to` are not yet
// implemented and render as disabled placeholders ("به‌زودی").
export type SettingsMenuItem = {
  key: string;
  label: string;
  icon: React.ElementType;
  to?: string;
};

export const SETTINGS_MENU: SettingsMenuItem[] = [
  { key: 'subscription', label: 'خرید اشتراک',       icon: CreditCardIcon,           to: '/admin/subscription' },
  { key: 'doctor',       label: 'مدیریت پزشک',        icon: UserIcon,                 to: '/admin/profile' },
  { key: 'appointment',  label: 'مدیریت نوبت دهی',    icon: CalendarDaysIcon },
  { key: 'clinic',       label: 'مدیریت مطب',         icon: BuildingOffice2Icon,      to: '/admin/my-clinic' },
  { key: 'services',     label: 'خدمات',              icon: WrenchScrewdriverIcon,    to: '/admin/clinic-services' },
  { key: 'payment',      label: 'مدیریت پرداخت',      icon: BanknotesIcon,            to: '/admin/my-financial' },
  { key: 'secretary',    label: 'مدیریت منشی',        icon: UsersIcon,                to: '/admin/my-secretaries' },
  { key: 'insurance',    label: 'مدیریت بیمه',        icon: ShieldCheckIcon,          to: '/admin/insurance-pricing' },
  { key: 'tags',         label: 'برچسب‌ها',           icon: TagIcon },
  { key: 'sms',          label: 'پیامک‌ها',           icon: ChatBubbleLeftRightIcon,  to: '/admin/sms-wallet' },
  { key: 'account',      label: 'حساب کاربری',        icon: UserCircleIcon },
];

// ── Shared item styling ──────────────────────────────────────────────────────
function itemStyle(active: boolean, disabled: boolean): React.CSSProperties {
  return {
    display: 'flex', alignItems: 'center', gap: 10,
    width: '100%', padding: '11px 14px', borderRadius: 'var(--r-sm)',
    fontSize: 14, fontWeight: active ? 700 : 500, textAlign: 'right',
    fontFamily: 'inherit', border: 'none', cursor: disabled ? 'not-allowed' : 'pointer',
    background: active ? 'var(--accent)' : 'transparent',
    color: active ? '#fff' : disabled ? 'var(--text-3)' : 'var(--text-2)',
    transition: 'background .14s, color .14s',
  };
}

function MenuRow({ item, active }: { item: SettingsMenuItem; active: boolean }) {
  const Icon = item.icon;
  const disabled = !item.to;
  const inner = (
    <>
      <Icon style={{ width: 18, height: 18, flexShrink: 0, opacity: disabled ? 0.6 : 1 }} />
      <span style={{ flex: 1 }}>{item.label}</span>
      {disabled && <span style={{ fontSize: 10.5, color: 'var(--text-3)' }}>به‌زودی</span>}
    </>
  );

  if (disabled) {
    return <button type="button" disabled style={itemStyle(false, true)}>{inner}</button>;
  }
  return (
    <Link
      to={item.to!}
      aria-current={active ? 'page' : undefined}
      style={itemStyle(active, false)}
      onMouseEnter={(e) => { if (!active) (e.currentTarget as HTMLElement).style.background = 'var(--surface-2)'; }}
      onMouseLeave={(e) => { if (!active) (e.currentTarget as HTMLElement).style.background = 'transparent'; }}
    >
      {inner}
    </Link>
  );
}

/**
 * SettingsLayout — presentational shell for the doctor/clinic settings area.
 * Renders a right-hand settings sub-navigation menu (desktop) beside the page
 * content. On mobile the menu is hidden (the standalone settings list page owns
 * navigation) and the content spans full width.
 *
 * @param active  key of the currently-open settings section (highlighted)
 * @param children  the section content (e.g. subscription plans)
 */
export default function SettingsLayout({ active, children }: { active: string; children: React.ReactNode }) {
  const [query, setQuery] = useState('');
  const items = useMemo(
    () => SETTINGS_MENU.filter((i) => i.label.includes(query.trim())),
    [query],
  );

  return (
    <div className="fade-in" style={{ maxWidth: 1180, margin: '0 auto' }}>
      <div className="grid grid-cols-1 lg:grid-cols-[260px_minmax(0,1fr)] gap-5">
        {/* Settings sub-nav — desktop only */}
        <aside
          className="hidden lg:block"
          aria-label="منوی تنظیمات"
          style={{
            background: 'var(--surface)', border: '1px solid var(--border)',
            borderRadius: 'var(--r-lg)', padding: 14, alignSelf: 'start',
            position: 'sticky', top: 'calc(var(--topbar-h) + 16px)',
          }}
        >
          <h2 className="section-title" style={{ fontSize: 16, marginBottom: 12 }}>تنظیمات</h2>

          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            background: 'var(--surface-2)', border: '1px solid var(--border)',
            borderRadius: 'var(--r-sm)', padding: '8px 12px', marginBottom: 12,
          }}>
            <MagnifyingGlassIcon style={{ width: 16, color: 'var(--text-3)', flexShrink: 0 }} />
            <input
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="جستجو در تنظیمات"
              aria-label="جستجو در تنظیمات"
              style={{
                border: 'none', outline: 'none', background: 'transparent',
                fontFamily: 'inherit', fontSize: 13, color: 'var(--text)', width: '100%',
              }}
            />
          </div>

          <nav style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            {items.map((item) => (
              <MenuRow key={item.key} item={item} active={item.key === active} />
            ))}
            {items.length === 0 && (
              <div style={{ padding: '12px 4px', fontSize: 13, color: 'var(--text-3)', textAlign: 'center' }}>
                موردی یافت نشد
              </div>
            )}
          </nav>
        </aside>

        {/* Section content */}
        <div style={{ minWidth: 0 }}>{children}</div>
      </div>
    </div>
  );
}
