import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { PlusIcon, PencilIcon, TrashIcon, WrenchScrewdriverIcon, BanknotesIcon } from '@heroicons/react/24/outline';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { ServiceSection, ServiceItem, ClinicStaff } from '../types';
import { formatRial } from '../lib/utils';
import Modal from '../components/ui/Modal';
import PriceInput from '../components/ui/PriceInput';
import ConfirmDialog from '../components/ui/ConfirmDialog';
import PageHeader from '../components/ui/PageHeader';
import ServiceTariffModal from '../components/ServiceTariffModal';
import SearchableSelect from '../components/ui/SearchableSelect';
import FeatureGate from '../components/ui/FeatureGate';

const sectionSchema = z.object({ name: z.string().min(1, 'نام بخش الزامی است') });
const itemSchema = z.object({
  name:                  z.string().min(1, 'نام سرویس الزامی است'),
  price_rials:           z.coerce.number().min(0, 'مبلغ نمی‌تواند منفی باشد'),
  staff_uuid:            z.string().optional(),
  insurance_covered:     z.boolean().optional(),
  insurance_price_rials: z.coerce.number().min(0).optional(),
});
type SectionForm = z.infer<typeof sectionSchema>;
type ItemForm    = z.infer<typeof itemSchema>;

const EMPTY_SECTIONS: ServiceSection[] = [];
const EMPTY_ITEMS: ServiceItem[] = [];

function ClinicServicesPageInner() {
  const qc = useQueryClient();

  const [selectedSection, setSelectedSection] = useState<ServiceSection | null>(null);
  const [sectionModal, setSectionModal] = useState<'create' | ServiceSection | null>(null);
  const [deleteSection, setDeleteSection] = useState<ServiceSection | null>(null);
  const [itemModal, setItemModal] = useState<'create' | ServiceItem | null>(null);
  const [deleteItem, setDeleteItem] = useState<ServiceItem | null>(null);
  const [tariffItem, setTariffItem] = useState<ServiceItem | null>(null);

  const { data: sectionsData, isLoading: sectionsLoading } = useQuery<ApiResponse<ServiceSection[]>>({
    queryKey: ['service-sections'],
    queryFn: () => api.get('/api/v1/service-sections'),
  });

  const { data: itemsData, isLoading: itemsLoading } = useQuery<ApiResponse<ServiceItem[]>>({
    queryKey: ['service-items', selectedSection?.uuid],
    queryFn: () => api.get(`/api/v1/service-items/${selectedSection!.uuid}`),
    enabled: !!selectedSection,
  });

  const { data: staffData } = useQuery<ApiResponse<ClinicStaff[]>>({
    queryKey: ['staff'],
    queryFn: () => api.get('/api/v1/staff'),
  });

  const sections = sectionsData?.data ?? EMPTY_SECTIONS;
  const items    = itemsData?.data ?? EMPTY_ITEMS;
  const staffOptions = (staffData?.data ?? []).filter((s) => s.active).map((s) => ({
    value: s.uuid,
    label: s.full_name,
  }));

  const sectionForm = useForm<SectionForm>({ resolver: zodResolver(sectionSchema) });
  const itemForm    = useForm<ItemForm>({ resolver: zodResolver(itemSchema) });

  const createSection = useMutation({
    mutationFn: (body: SectionForm) => api.post('/api/v1/service-section', body),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['service-sections'] }); setSectionModal(null); sectionForm.reset(); toast.success('بخش ایجاد شد'); },
    onError: (e: any) => toast.error(e.message),
  });

  const editSection = useMutation({
    mutationFn: ({ uuid, body }: { uuid: string; body: SectionForm }) =>
      api.patch(`/api/v1/service-section/${uuid}`, body),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['service-sections'] }); setSectionModal(null); toast.success('بخش ویرایش شد'); },
    onError: (e: any) => toast.error(e.message),
  });

  const delSection = useMutation({
    mutationFn: (uuid: string) => api.delete(`/api/v1/service-section/${uuid}`),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['service-sections'] });
      if (selectedSection?.uuid === deleteSection?.uuid) setSelectedSection(null);
      setDeleteSection(null);
      toast.success('بخش حذف شد');
    },
    onError: (e: any) => { toast.error(e.message); setDeleteSection(null); },
  });

  const createItem = useMutation({
    mutationFn: (body: ItemForm & { section_uuid: string }) => api.post('/api/v1/service-item', body),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['service-items', selectedSection?.uuid] }); setItemModal(null); itemForm.reset(); toast.success('سرویس ایجاد شد'); },
    onError: (e: any) => toast.error(e.message),
  });

  const editItem = useMutation({
    mutationFn: ({ uuid, body }: { uuid: string; body: ItemForm }) =>
      api.patch(`/api/v1/service-item/${uuid}`, body),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['service-items', selectedSection?.uuid] }); setItemModal(null); toast.success('سرویس ویرایش شد'); },
    onError: (e: any) => toast.error(e.message),
  });

  const delItem = useMutation({
    mutationFn: (uuid: string) => api.delete(`/api/v1/service-item/${uuid}`),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['service-items', selectedSection?.uuid] }); setDeleteItem(null); toast.success('سرویس حذف شد'); },
    onError: (e: any) => {
      if (e.code === 'ERR_SERVICE_ITEM_IN_USE') {
        toast.error('این سرویس در پرونده بیمار استفاده شده و قابل حذف نیست');
      } else {
        toast.error(e.message);
      }
      setDeleteItem(null);
    },
  });

  const openEditSection = (s: ServiceSection) => {
    sectionForm.reset({ name: s.name });
    setSectionModal(s);
  };

  const openEditItem = (item: ServiceItem) => {
    itemForm.reset({
      name: item.name,
      price_rials: item.price_rials,
      staff_uuid: item.staff?.uuid ?? '',
      insurance_covered: item.insurance_covered ?? false,
      insurance_price_rials: item.insurance_price_rials ?? 0,
    });
    setItemModal(item);
  };

  return (
    <>
      <PageHeader title="سرویس‌های کلینیک" description="مدیریت بخش‌ها و سرویس‌های کلینیک" />

      <div style={{ display: 'grid', gridTemplateColumns: '300px 1fr', gap: 16, alignItems: 'start' }}>
        {/* ستون بخش‌ها */}
        <div className="card">
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '14px 16px', borderBottom: '1px solid var(--border)',
          }}>
            <b style={{ fontSize: 14 }}>بخش‌ها</b>
            <button
              className="btn primary sm"
              style={{ display: 'flex', alignItems: 'center', gap: 4 }}
              onClick={() => { sectionForm.reset(); setSectionModal('create'); }}
            >
              <PlusIcon style={{ width: 14 }} /> بخش جدید
            </button>
          </div>

          <div style={{ padding: '8px 0' }}>
            {sectionsLoading ? (
              <div style={{ color: 'var(--text-3)', fontSize: 13, padding: '12px 16px' }}>در حال بارگذاری...</div>
            ) : sections.length === 0 ? (
              <div style={{ padding: '32px 16px', textAlign: 'center', color: 'var(--text-3)' }}>
                <WrenchScrewdriverIcon style={{ width: 32, margin: '0 auto 10px', display: 'block', opacity: 0.4 }} />
                <div style={{ fontSize: 13 }}>بخشی ثبت نشده است</div>
              </div>
            ) : (
              sections.map((s) => (
                <div
                  key={s.uuid}
                  style={{
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                    padding: '10px 14px', cursor: 'pointer',
                    background: selectedSection?.uuid === s.uuid ? 'var(--primary-subtle)' : 'transparent',
                    borderRight: selectedSection?.uuid === s.uuid ? '3px solid var(--primary)' : '3px solid transparent',
                    transition: 'all 0.15s',
                  }}
                  onClick={() => setSelectedSection(s)}
                >
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <WrenchScrewdriverIcon style={{
                      width: 16,
                      color: selectedSection?.uuid === s.uuid ? 'var(--primary)' : 'var(--text-3)',
                      transition: 'color 0.15s',
                    }} />
                    <span style={{
                      fontSize: 13.5, fontWeight: selectedSection?.uuid === s.uuid ? 600 : 400,
                      color: selectedSection?.uuid === s.uuid ? 'var(--primary)' : 'var(--text-1)',
                    }}>
                      {s.name}
                    </span>
                  </div>
                  <div style={{ display: 'flex', gap: 4 }} onClick={(e) => e.stopPropagation()}>
                    <button
                      className="btn sm"
                      style={{ opacity: 0.7 }}
                      onClick={() => openEditSection(s)}
                      title="ویرایش"
                    >
                      <PencilIcon style={{ width: 13 }} />
                    </button>
                    <button
                      className="btn sm"
                      style={{ opacity: 0.7 }}
                      onClick={() => setDeleteSection(s)}
                      title="حذف"
                    >
                      <TrashIcon style={{ width: 13 }} />
                    </button>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>

        {/* ستون آیتم‌ها */}
        <div className="card">
          {!selectedSection ? (
            <div style={{
              border: '2px dashed var(--border)', borderRadius: 10,
              margin: 16, padding: '60px 0', textAlign: 'center', color: 'var(--text-3)',
            }}>
              <WrenchScrewdriverIcon style={{ width: 40, margin: '0 auto 14px', display: 'block', opacity: 0.35 }} />
              <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text-2)' }}>یک بخش انتخاب کنید</div>
              <div style={{ fontSize: 13, marginTop: 4 }}>تا سرویس‌های آن را مشاهده و مدیریت کنید</div>
            </div>
          ) : (
            <>
              {/* toolbar بخش انتخاب‌شده */}
              <div style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '14px 16px', borderBottom: '1px solid var(--border)',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <WrenchScrewdriverIcon style={{ width: 16, color: 'var(--primary)' }} />
                  <b style={{ fontSize: 14 }}>{selectedSection.name}</b>
                  {!itemsLoading && (
                    <span className="badge gray" style={{ fontSize: 11 }}>{items.length} سرویس</span>
                  )}
                </div>
                <button
                  className="btn primary sm"
                  style={{ display: 'flex', alignItems: 'center', gap: 4 }}
                  onClick={() => { itemForm.reset({ price_rials: 0, staff_uuid: '', insurance_covered: false, insurance_price_rials: 0 }); setItemModal('create'); }}
                >
                  <PlusIcon style={{ width: 14 }} /> سرویس جدید
                </button>
              </div>

              {itemsLoading ? (
                <div style={{ color: 'var(--text-3)', fontSize: 13, padding: '16px 16px' }}>در حال بارگذاری...</div>
              ) : items.length === 0 ? (
                <div style={{ padding: '48px 0', textAlign: 'center', color: 'var(--text-3)' }}>
                  <PlusIcon style={{ width: 32, margin: '0 auto 12px', display: 'block', opacity: 0.35 }} />
                  <div style={{ fontWeight: 500, color: 'var(--text-2)', marginBottom: 4 }}>سرویسی در این بخش وجود ندارد</div>
                  <button
                    className="btn primary sm"
                    style={{ marginTop: 12 }}
                    onClick={() => { itemForm.reset({ price_rials: 0, staff_uuid: '', insurance_covered: false, insurance_price_rials: 0 }); setItemModal('create'); }}
                  >
                    افزودن سرویس
                  </button>
                </div>
              ) : (
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                  <thead>
                    <tr style={{ background: 'oklch(0.97 0.01 256)', borderBottom: '1px solid var(--border)' }}>
                      <th style={{ textAlign: 'right', padding: '10px 16px', fontWeight: 600, color: 'var(--text-2)' }}>نام سرویس</th>
                      <th style={{ textAlign: 'right', padding: '10px 16px', fontWeight: 600, color: 'var(--text-2)' }}>قیمت</th>
                      <th style={{ textAlign: 'right', padding: '10px 16px', fontWeight: 600, color: 'var(--text-2)' }}>پرسنل مسئول</th>
                      <th style={{ textAlign: 'right', padding: '10px 16px', fontWeight: 600, color: 'var(--text-2)' }}>عملیات</th>
                    </tr>
                  </thead>
                  <tbody>
                    {items.map((item, idx) => (
                      <tr
                        key={item.uuid}
                        style={{
                          borderBottom: '1px solid var(--border)',
                          background: idx % 2 === 1 ? 'oklch(0.985 0.005 256)' : 'transparent',
                        }}
                      >
                        <td style={{ padding: '11px 16px', fontWeight: 500 }}>
                          {item.name}
                          {item.insurance_covered && (
                            <span className="badge green" style={{ fontSize: 10, marginInlineStart: 6 }}>
                              <span className="bdot" />بیمه
                            </span>
                          )}
                        </td>
                        <td style={{ padding: '11px 16px', color: 'var(--primary)', fontWeight: 600 }}>
                          {formatRial(item.price_rials)}
                        </td>
                        <td style={{ padding: '11px 16px' }}>
                          {item.staff ? (
                            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                              <div style={{
                                width: 22, height: 22, borderRadius: '50%',
                                background: 'linear-gradient(145deg, oklch(0.62 0.15 162), oklch(0.48 0.16 162))',
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                fontSize: 10, fontWeight: 700, color: '#fff', flexShrink: 0,
                              }}>
                                {item.staff.full_name.charAt(0)}
                              </div>
                              <span style={{ fontSize: 13 }}>{item.staff.full_name}</span>
                            </div>
                          ) : (
                            <span style={{ color: 'var(--text-3)' }}>—</span>
                          )}
                        </td>
                        <td style={{ padding: '11px 16px' }}>
                          <div style={{ display: 'flex', gap: 4 }}>
                            <button className="btn sm" onClick={() => openEditItem(item)} title="ویرایش">
                              <PencilIcon style={{ width: 13 }} />
                            </button>
                            <button className="btn sm" onClick={() => setTariffItem(item)} title="تعرفه‌های سالانه">
                              <BanknotesIcon style={{ width: 13 }} />
                            </button>
                            <button className="btn sm" onClick={() => setDeleteItem(item)} title="حذف">
                              <TrashIcon style={{ width: 13 }} />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </>
          )}
        </div>
      </div>

      {/* Modal بخش */}
      <Modal
        open={sectionModal !== null}
        onClose={() => setSectionModal(null)}
        title={sectionModal === 'create' ? 'بخش جدید' : 'ویرایش بخش'}
      >
        <form onSubmit={sectionForm.handleSubmit((d) => {
          if (sectionModal === 'create') createSection.mutate(d);
          else if (sectionModal !== null && typeof sectionModal === 'object') editSection.mutate({ uuid: sectionModal.uuid, body: d });
        })}>
          <div className="field">
            <label>نام بخش *</label>
            <input {...sectionForm.register('name')} placeholder="مثلاً: تزریقات" />
            {sectionForm.formState.errors.name && (
              <span className="field-error">{sectionForm.formState.errors.name.message}</span>
            )}
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
            <button type="submit" className="btn primary" disabled={createSection.isPending || editSection.isPending}>ذخیره</button>
            <button type="button" className="btn" onClick={() => setSectionModal(null)}>انصراف</button>
          </div>
        </form>
      </Modal>

      {/* Modal آیتم */}
      <Modal
        open={itemModal !== null}
        onClose={() => setItemModal(null)}
        title={itemModal === 'create' ? 'سرویس جدید' : 'ویرایش سرویس'}
      >
        <form onSubmit={itemForm.handleSubmit((d) => {
          if (itemModal === 'create' && selectedSection) {
            createItem.mutate({ ...d, section_uuid: selectedSection.uuid });
          } else if (itemModal !== null && typeof itemModal === 'object') {
            editItem.mutate({ uuid: itemModal.uuid, body: d });
          }
        })}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div className="field">
              <label>نام سرویس *</label>
              <input {...itemForm.register('name')} placeholder="مثلاً: سرم ۵۰۰cc" />
              {itemForm.formState.errors.name && (
                <span className="field-error">{itemForm.formState.errors.name.message}</span>
              )}
            </div>
            <div className="field">
              <label>قیمت (ریال) *</label>
              <PriceInput
                value={itemForm.watch('price_rials') ?? 0}
                onChange={(v) => itemForm.setValue('price_rials', v)}
                placeholder="۸۵,۰۰۰"
                min={0}
              />
            </div>
            <div className="field">
              <label>پرسنل مسئول</label>
              <SearchableSelect
                options={staffOptions}
                value={itemForm.watch('staff_uuid') ?? ''}
                onChange={(v) => itemForm.setValue('staff_uuid', v != null ? String(v) : undefined)}
                placeholder="انتخاب پرسنل (اختیاری)"
                isClearable
              />
            </div>
            <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 13.5 }}>
              <input
                type="checkbox"
                checked={itemForm.watch('insurance_covered') ?? false}
                onChange={(e) => itemForm.setValue('insurance_covered', e.target.checked)}
              />
              این خدمت شامل بیمه می‌شود
            </label>
            {itemForm.watch('insurance_covered') && (
              <div className="field">
                <label>قیمت با بیمه (ریال)</label>
                <PriceInput
                  value={itemForm.watch('insurance_price_rials') ?? 0}
                  onChange={(v) => itemForm.setValue('insurance_price_rials', v)}
                  placeholder="سهم بیمار با بیمه"
                  min={0}
                />
              </div>
            )}
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
            <button type="submit" className="btn primary" disabled={createItem.isPending || editItem.isPending}>ذخیره</button>
            <button type="button" className="btn" onClick={() => setItemModal(null)}>انصراف</button>
          </div>
        </form>
      </Modal>

      <ServiceTariffModal item={tariffItem} onClose={() => setTariffItem(null)} />

      {/* Confirm حذف بخش */}
      <ConfirmDialog
        open={!!deleteSection}
        title="حذف بخش"
        message={`آیا مطمئن هستید که می‌خواهید بخش «${deleteSection?.name}» را حذف کنید؟`}
        confirmLabel="حذف"
        onConfirm={() => deleteSection && delSection.mutate(deleteSection.uuid)}
        onCancel={() => setDeleteSection(null)}
        loading={delSection.isPending}
      />

      {/* Confirm حذف آیتم */}
      <ConfirmDialog
        open={!!deleteItem}
        title="حذف سرویس"
        message={`آیا مطمئن هستید که می‌خواهید سرویس «${deleteItem?.name}» را حذف کنید؟`}
        confirmLabel="حذف"
        onConfirm={() => deleteItem && delItem.mutate(deleteItem.uuid)}
        onCancel={() => setDeleteItem(null)}
        loading={delItem.isPending}
      />
    </>
  );
}

export default function ClinicServicesPage() {
  return (
    <FeatureGate feature="services">
      <ClinicServicesPageInner />
    </FeatureGate>
  );
}
