import { useMemo, useState, type ReactNode } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { PlusIcon, PencilIcon, MagnifyingGlassIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import { formatRial } from '../lib/utils';
import InsuranceModal, { Contract, InsuranceOption, KIND_LABEL, buildInsurancePayload } from './InsuranceModal';

/** Case-insensitive filter over insurance name (and code) — the "جستجو در بیمه ها..." box. */
export function filterInsurances(list: Contract[], query: string): Contract[] {
  const q = query.trim().toLowerCase();
  if (!q) return list;
  return list.filter((c) =>
    (c.insurance_name ?? '').toLowerCase().includes(q) ||
    String(c.insurance_id).includes(q),
  );
}

export default function TenantInsuranceContracts() {
  const qc = useQueryClient();
  const [modalOpen, setModalOpen] = useState(false);
  const [editContract, setEditContract] = useState<Contract | null>(null);
  const [search, setSearch] = useState('');

  const contractsQuery = useQuery({
    queryKey: ['tenant-insurances'],
    queryFn: () => api.get('/api/v1/billing/tenant-insurances'),
  });

  const pricingQuery = useQuery({
    queryKey: ['insurance-pricing'],
    queryFn: () => api.get('/api/v1/insurance-pricing'),
  });

  const contracts: Contract[] = (contractsQuery.data as any)?.data?.data ?? [];
  const allInsurances: InsuranceOption[] = (pricingQuery.data as any)?.data?.insurances ?? [];
  const activeIds = new Set(contracts.map((c) => c.insurance_id));
  const available = allInsurances.filter((i) => !activeIds.has(i.insurance_id));

  const rows = useMemo(() => filterInsurances(contracts, search), [contracts, search]);

  const invalidate = () => qc.invalidateQueries({ queryKey: ['tenant-insurances'] });

  const saveMut = useMutation({
    mutationFn: (payload: ReturnType<typeof buildInsurancePayload>) =>
      editContract
        ? api.patch(`/api/v1/billing/tenant-insurances/${editContract.uuid}`, payload)
        : api.post('/api/v1/billing/tenant-insurances', payload),
    onSuccess: () => {
      toast.success(editContract ? 'قرارداد بیمه ویرایش شد' : 'قرارداد بیمه فعال شد');
      closeModal();
      invalidate();
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const toggleMut = useMutation({
    mutationFn: (c: Contract) =>
      api.patch(`/api/v1/billing/tenant-insurances/${c.uuid}`, { is_active: !c.is_active }),
    onSuccess: () => invalidate(),
    onError: (e: Error) => toast.error(e.message),
  });

  const openAdd = () => { setEditContract(null); setModalOpen(true); };
  const openEdit = (c: Contract) => { setEditContract(c); setModalOpen(true); };
  const closeModal = () => { setModalOpen(false); setEditContract(null); };

  return (
    <div className="card" style={{ padding: 20 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
        <h2 style={{ fontSize: 15, fontWeight: 700, margin: 0 }}>مدیریت بیمه</h2>
        <button className="btn primary sm" onClick={openAdd}>
          <PlusIcon style={{ width: 15 }} /> افزودن بیمه
        </button>
      </div>

      <div style={{ position: 'relative', marginBottom: 16 }}>
        <MagnifyingGlassIcon style={{ width: 16, position: 'absolute', insetInlineStart: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)' }} />
        <input
          className="input"
          style={{ paddingInlineStart: 36 }}
          placeholder="جستجو در بیمه ها..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      {contractsQuery.isLoading ? (
        <div className="muted" style={{ fontSize: 13 }}>در حال بارگذاری...</div>
      ) : rows.length === 0 ? (
        <div style={{ fontSize: 12.5, color: 'var(--text-3)', padding: '16px 0', textAlign: 'center' }}>
          {search ? 'بیمه‌ای یافت نشد.' : 'هنوز با هیچ بیمه‌ای قرارداد ندارید.'}
        </div>
      ) : (
        <>
          {/* Desktop table */}
          <div className="hidden md:block" style={{ overflowX: 'auto' }}>
            <table className="data-table" style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ textAlign: 'start', color: 'var(--text-3)', fontSize: 12 }}>
                  <th style={{ padding: '10px 12px', textAlign: 'start' }}>ردیف</th>
                  <th style={{ padding: '10px 12px', textAlign: 'start' }}>نام بیمه</th>
                  <th style={{ padding: '10px 12px', textAlign: 'start' }}>کد</th>
                  <th style={{ padding: '10px 12px', textAlign: 'start' }}>نوع بیمه</th>
                  <th style={{ padding: '10px 12px', textAlign: 'start' }}>وضعیت</th>
                  <th style={{ padding: '10px 12px', textAlign: 'start' }}>عملیات</th>
                </tr>
              </thead>
              <tbody>
                {rows.map((c, i) => (
                  <tr key={c.uuid} style={{ borderTop: '1px solid var(--border)', fontSize: 13 }}>
                    <td style={{ padding: '12px' }}>{i + 1}</td>
                    <td style={{ padding: '12px', fontWeight: 600 }}>
                      {c.insurance_name ?? `#${c.insurance_id}`}
                      <div style={{ fontSize: 11, color: 'var(--text-3)', fontWeight: 400, marginTop: 2 }}>
                        پوشش {c.coverage_percent}٪
                        {c.franchise_rials > 0 && ` · فرانشیز ${formatRial(c.franchise_rials)}`}
                        {c.annual_ceiling_rials != null && ` · سقف ${formatRial(c.annual_ceiling_rials)}`}
                      </div>
                    </td>
                    <td style={{ padding: '12px', color: 'var(--text-2)' }} dir="ltr">{c.insurance_id}</td>
                    <td style={{ padding: '12px' }}>{KIND_LABEL[c.insurance_kind ?? ''] ?? c.insurance_kind ?? '—'}</td>
                    <td style={{ padding: '12px' }}>
                      <StatusToggle contract={c} onToggle={() => toggleMut.mutate(c)} disabled={toggleMut.isPending} />
                    </td>
                    <td style={{ padding: '12px' }}>
                      <button className="mini-btn" title="ویرایش" onClick={() => openEdit(c)}>
                        <PencilIcon style={{ width: 15 }} />
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Mobile cards */}
          <div className="md:hidden" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {rows.map((c) => (
              <div key={c.uuid} style={{ border: '1px solid var(--border)', borderRadius: 12, padding: 14 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{c.insurance_name ?? `#${c.insurance_id}`}</div>
                  <button className="mini-btn" title="ویرایش" onClick={() => openEdit(c)}>
                    <PencilIcon style={{ width: 15 }} />
                  </button>
                </div>
                <Row label="کد" value={<span dir="ltr">{c.insurance_id}</span>} />
                <Row label="نوع بیمه" value={KIND_LABEL[c.insurance_kind ?? ''] ?? c.insurance_kind ?? '—'} />
                <Row label="وضعیت" value={<StatusToggle contract={c} onToggle={() => toggleMut.mutate(c)} disabled={toggleMut.isPending} />} />
              </div>
            ))}
          </div>
        </>
      )}

      <InsuranceModal
        open={modalOpen}
        editContract={editContract}
        options={editContract ? allInsurances : available}
        onClose={closeModal}
        onSubmit={(payload) => saveMut.mutate(payload)}
        isPending={saveMut.isPending}
      />
    </div>
  );
}

function Row({ label, value }: { label: string; value: ReactNode }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '6px 0', fontSize: 12.5, borderTop: '1px solid var(--border-2)' }}>
      <span style={{ color: 'var(--text-3)' }}>{label}:</span>
      <span>{value}</span>
    </div>
  );
}

function StatusToggle({ contract, onToggle, disabled }: { contract: Contract; onToggle: () => void; disabled?: boolean }) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={contract.is_active}
      aria-label={contract.is_active ? 'غیرفعال کردن' : 'فعال کردن'}
      onClick={onToggle}
      disabled={disabled}
      style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: 'none', border: 'none', cursor: disabled ? 'default' : 'pointer', padding: 0 }}
    >
      <span style={{
        width: 36, height: 20, borderRadius: 999, position: 'relative', transition: 'background .2s',
        background: contract.is_active ? 'var(--primary)' : 'var(--border)',
      }}>
        <span style={{
          position: 'absolute', top: 2, width: 16, height: 16, borderRadius: 999, background: '#fff', transition: 'inset-inline .2s',
          insetInlineStart: contract.is_active ? 18 : 2,
        }} />
      </span>
      <span style={{ fontSize: 12, color: contract.is_active ? 'var(--success)' : 'var(--text-3)' }}>
        {contract.is_active ? 'فعال' : 'غیرفعال'}
      </span>
    </button>
  );
}
