import React, { useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { useAuthStore } from '../../stores/authStore';
import { menuForRole } from './SettingsLayout';
import { SearchHeaderP } from '../../pages/subscriptionIcons';

/**
 * PurchaseSubscriptionSidebar — pixel-faithful port of clinic-pro-tauri's
 * `PurchaseSubscriptionSidebar.jsx` (title + search + tab list, orange active
 * pill #f17732). Unlike the Tauri original it does not switch content inline;
 * each item is a real admin route (from SETTINGS_MENU / menuForRole), so the
 * clinicpro routing architecture is preserved. `active` marks the open section.
 */
export default function PurchaseSubscriptionSidebar({ active }: { active: string }) {
  const primaryRole = useAuthStore((s) => s.primaryRole);
  const [query, setQuery] = useState('');
  const items = useMemo(
    () => menuForRole(primaryRole).filter((i) => i.label.includes(query.trim())),
    [primaryRole, query],
  );

  return (
    <div
      dir="ltr"
      style={{
        flexShrink: 0,
        borderRadius: 8,
        background: 'transparent',
        alignSelf: 'start',
        position: 'sticky',
        top: 'calc(var(--topbar-h) + 16px)',
      }}
      className="w-full md:w-[240px] lg:w-[280px] md:py-4"
    >
      {/* Mobile/Tablet: horizontal scrollable tab strip */}
      <div
        className="flex md:hidden"
        style={{
          flexDirection: 'row-reverse', overflowX: 'auto', gap: 8,
          padding: '12px 8px', whiteSpace: 'nowrap', scrollbarWidth: 'none',
        }}
      >
        {items.map((item) => {
          const isActive = item.key === active;
          const inner = (
            <span style={{
              flexShrink: 0, borderRadius: 12, padding: '8px 16px', minWidth: 'auto',
              display: 'inline-block', fontSize: 14, fontWeight: isActive ? 700 : 500,
              background: isActive ? '#f17732' : 'var(--surface-2)',
              color: isActive ? '#FFFFFF' : 'var(--text-2)', cursor: item.to ? 'pointer' : 'not-allowed',
            }}>{item.label}</span>
          );
          return item.to
            ? <Link key={item.key} to={item.to}>{inner}</Link>
            : <span key={item.key}>{inner}</span>;
        })}
      </div>

      {/* Desktop: Title + Search + vertical list */}
      <div className="hidden md:block">
        <div style={{
          fontSize: 16, fontWeight: 800, color: 'var(--text-2)', textAlign: 'left',
          marginBottom: 10, padding: '0 16px',
        }}>
          تنظیمات
        </div>

        <div style={{ padding: '0 16px', marginBottom: 16 }}>
          <div style={{
            display: 'flex', alignItems: 'center', flexDirection: 'row-reverse', gap: 8,
            background: 'var(--surface)', border: '1px solid var(--border)',
            borderRadius: 'var(--r-sm)', padding: '8px 12px',
          }}>
            <SearchHeaderP />
            <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%',
                textAlign: 'right', direction: 'rtl',
              }}
            />
          </div>
        </div>

        <nav style={{ padding: '0 16px' }}>
          {items.map((item) => {
            const isActive = item.key === active;
            const rowStyle: React.CSSProperties = {
              borderRadius: 12, height: 44, marginBottom: 8,
              display: 'flex', alignItems: 'center', justifyContent: 'flex-start',
              padding: '0 14px', fontSize: 16, fontWeight: isActive ? 700 : 500,
              lineHeight: 1, textAlign: 'left',
              background: isActive ? '#f17732' : 'transparent',
              color: isActive ? '#FFFFFF' : 'var(--text-2)',
              cursor: item.to ? 'pointer' : 'not-allowed',
              transition: 'background .14s',
            };
            const inner = <span style={{ flex: 1 }}>{item.label}</span>;
            if (!item.to) {
              return <div key={item.key} style={{ ...rowStyle, opacity: 0.55 }}>{inner}</div>;
            }
            return (
              <Link
                key={item.key}
                to={item.to}
                aria-current={isActive ? 'page' : undefined}
                style={rowStyle}
                onMouseEnter={(e) => { if (!isActive) (e.currentTarget as HTMLElement).style.background = 'var(--surface-2)'; }}
                onMouseLeave={(e) => { if (!isActive) (e.currentTarget as HTMLElement).style.background = 'transparent'; }}
              >
                {inner}
              </Link>
            );
          })}
          {items.length === 0 && (
            <div style={{ padding: '12px 4px', fontSize: 13, color: 'var(--text-3)', textAlign: 'center' }}>
              موردی یافت نشد
            </div>
          )}
        </nav>
      </div>
    </div>
  );
}
