import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { XMarkIcon } from '@heroicons/react/24/outline';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { Appointment } from '../types';
import Modal from './ui/Modal';
import SearchableSelect from './ui/SearchableSelect';
import { digitsOnly } from '../lib/utils';

interface Option { uuid: string; name?: string }

export interface AppointmentFilters {
  name: string;
  nationalCode: string;
  sectionUuid: string;
  itemUuid: string;
  /** toolbar «پرسنل را انتخاب کنید...» select — not part of the modal */
  staffUuid: string;
  statuses: string[];
  gender: 'female' | 'male' | 'both';
}

export const EMPTY_FILTERS: AppointmentFilters = {
  name: '', nationalCode: '', sectionUuid: '', itemUuid: '', staffUuid: '', statuses: [], gender: 'both',
};

// design's 6 checkboxes; لغو شده covers both cancel reasons
const STATUS_OPTIONS: [string, string][] = [
  ['pending', 'ثبت شده'],
  ['confirmed', 'قطعی شده'],
  ['following_up', 'در حال پیگیری'],
  ['salon', 'سالن'],
  ['completed', 'ویزیت شده'],
  ['cancelled', 'لغو شده'],
];

/** Pure client-side filter of the loaded day's appointments (Figma فیلترها). */
export function applyAppointmentFilters(items: Appointment[], f: AppointmentFilters): Appointment[] {
  return items.filter(a => {
    if (f.name && !(a.patient_name ?? '').includes(f.name)) return false;
    if (f.nationalCode && !(a.patient_national_code ?? '').includes(f.nationalCode)) return false;
    if (f.sectionUuid && a.service_section?.uuid !== f.sectionUuid) return false;
    if (f.itemUuid && a.service_item?.uuid !== f.itemUuid) return false;
    if (f.staffUuid && a.staff?.uuid !== f.staffUuid) return false;
    if (f.statuses.length) {
      const matches = f.statuses.some(s =>
        s === 'cancelled' ? a.status.startsWith('cancelled') : a.status === s);
      if (!matches) return false;
    }
    if (f.gender !== 'both' && (a.patient_gender ?? '') !== f.gender) return false;
    return true;
  });
}

/** فیلترها (filter-desktop.pdf) — name/national-code search, بخش/سرویس, status checkboxes, gender. */
export default function AppointmentFiltersModal({ value, onApply, onClose }: {
  value: AppointmentFilters; onApply: (f: AppointmentFilters) => void; onClose: () => void;
}) {
  const [f, setF] = useState<AppointmentFilters>(value);

  const sectionsQ = useQuery<ApiResponse<Option[]>>({ queryKey: ['service-sections'], queryFn: () => api.get('/api/v1/service-sections') });
  const itemsQ = useQuery<ApiResponse<Option[]>>({
    queryKey: ['service-items', f.sectionUuid],
    queryFn: () => api.get(`/api/v1/service-items/${f.sectionUuid}`),
    enabled: !!f.sectionUuid,
  });

  const toggleStatus = (s: string) => setF(v => ({
    ...v,
    statuses: v.statuses.includes(s) ? v.statuses.filter(x => x !== s) : [...v.statuses, s],
  }));

  const label = { fontSize: 12.5, color: 'var(--text-3)' } as const;

  return (
    <Modal open title="فیلترها" onClose={onClose}>
      <div>
        <div style={{ display: 'flex', justifyContent: 'flex-start', marginBottom: 8 }}>
          <button className="btn sm ghost" style={{ color: 'var(--accent)' }} onClick={() => setF(EMPTY_FILTERS)}>
            <XMarkIcon style={{ width: 14 }} /> حذف همه
          </button>
        </div>

        <label style={label}>جستجو براساس نام</label>
        <div className="field" style={{ margin: '6px 0 12px' }}>
          <input value={f.name} onChange={e => setF(v => ({ ...v, name: e.target.value }))} placeholder="نام مراجعه کننده را وارد کنید..." />
        </div>
        <label style={label}>جستجو براساس کد ملی</label>
        <div className="field" style={{ margin: '6px 0 12px' }}>
          <input value={f.nationalCode} onChange={e => setF(v => ({ ...v, nationalCode: digitsOnly(e.target.value, 10) }))} placeholder="کد ملی مراجعه کننده را وارد کنید..." inputMode="numeric" dir="ltr" />
        </div>

        <label style={label}>بخش</label>
        <div style={{ margin: '6px 0 12px' }}>
          <SearchableSelect
            options={(sectionsQ.data?.data ?? []).map(o => ({ value: o.uuid, label: o.name ?? '' }))}
            value={f.sectionUuid || null}
            onChange={v => setF(prev => ({ ...prev, sectionUuid: v ? String(v) : '', itemUuid: '' }))}
            placeholder="انتخاب بخش"
            isLoading={sectionsQ.isLoading}
            isClearable
            height={38}
          />
        </div>
        <label style={label}>سرویس</label>
        <div style={{ margin: '6px 0 14px' }}>
          <SearchableSelect
            options={(itemsQ.data?.data ?? []).map(o => ({ value: o.uuid, label: o.name ?? '' }))}
            value={f.itemUuid || null}
            onChange={v => setF(prev => ({ ...prev, itemUuid: v ? String(v) : '' }))}
            placeholder="انتخاب سرویس"
            isDisabled={!f.sectionUuid}
            isLoading={itemsQ.isLoading}
            isClearable
            height={38}
          />
        </div>

        <div style={{ fontSize: 13.5, fontWeight: 700, marginBottom: 8 }}>وضعیت نوبت</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 14 }}>
          {STATUS_OPTIONS.map(([v, l]) => (
            <label key={v} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13, cursor: 'pointer' }}>
              <input type="checkbox" checked={f.statuses.includes(v)} onChange={() => toggleStatus(v)} /> {l}
            </label>
          ))}
        </div>

        <div style={{ borderTop: '1px solid var(--border)', paddingTop: 12, marginBottom: 16 }}>
          <div style={{ fontSize: 13.5, fontWeight: 700, marginBottom: 8 }}>جنسیت</div>
          {([['female', 'خانم'], ['male', 'آقا'], ['both', 'هر دو']] as const).map(([v, l]) => (
            <label key={v} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, cursor: 'pointer', marginBottom: 6 }}>
              <input type="radio" name="gender" checked={f.gender === v} onChange={() => setF(x => ({ ...x, gender: v }))} /> {l}
            </label>
          ))}
        </div>

        <button className="btn primary" style={{ width: '100%' }} onClick={() => { onApply(f); onClose(); }}>
          اعمال تغییرات
        </button>
      </div>
    </Modal>
  );
}
