import { useEffect, useState } from 'react';
import Modal from './ui/Modal';
import SearchableSelect from './ui/SearchableSelect';
import PersianDateInput from './ui/PersianDateInput';
import { isoToUnix, rialToToman, tomanToRial, unixToIso } from '../lib/utils';
import { digitsOnly } from '../lib/utils';

export interface InsuranceOption {
  insurance_id: number;
  insurance_name: string;
  type: string;
}

export interface Contract {
  uuid: string;
  insurance_id: number;
  insurance_name: string | null;
  insurance_kind: string | null;
  version: number;
  is_active: boolean;
  coverage_percent: number;
  franchise_rials: number;
  annual_ceiling_rials: number | null;
  kind: string | null;
  effective_from: number;
  effective_to: number | null;
}

export interface InsuranceFormValues {
  insuranceId: string;
  kind: string;
  effectiveFrom: string; // Y-m-d
  effectiveTo: string;   // Y-m-d
  coverage: string;
  franchise: string;     // toman
  ceiling: string;       // toman
}

export const KIND_LABEL: Record<string, string> = {
  basic: 'پایه',
  supplementary: 'تکمیلی',
};

export const EMPTY_FORM: InsuranceFormValues = {
  insuranceId: '', kind: 'basic', effectiveFrom: '', effectiveTo: '',
  coverage: '', franchise: '', ceiling: '',
};

/** Map a contract to editable form values (rials → toman, unix → Y-m-d). */
export function contractToForm(c: Contract): InsuranceFormValues {
  return {
    insuranceId: String(c.insurance_id),
    kind: c.kind ?? c.insurance_kind ?? 'basic',
    effectiveFrom: unixToIso(c.effective_from),
    effectiveTo: unixToIso(c.effective_to),
    coverage: String(c.coverage_percent ?? ''),
    franchise: c.franchise_rials != null ? String(rialToToman(c.franchise_rials)) : '',
    ceiling: c.annual_ceiling_rials != null ? String(rialToToman(c.annual_ceiling_rials)) : '',
  };
}

/** Build the API payload from form values (toman → rials, Y-m-d → unix). */
export function buildInsurancePayload(v: InsuranceFormValues) {
  return {
    insurance_id: Number(v.insuranceId),
    kind: v.kind || null,
    coverage_percent: Number(v.coverage) || 0,
    franchise_rials: tomanToRial(Number(v.franchise) || 0),
    annual_ceiling_rials: v.ceiling === '' ? null : tomanToRial(Number(v.ceiling)),
    effective_from: isoToUnix(v.effectiveFrom),
    effective_to: isoToUnix(v.effectiveTo),
  };
}

interface Props {
  open: boolean;
  editContract: Contract | null;
  /** Insurance catalog options; in edit mode all are shown, in add mode only the available ones. */
  options: InsuranceOption[];
  /** Insurance kind of the active tab ('basic'|'supplementary'); assigned to new contracts, not user-editable. */
  kind: string;
  onClose: () => void;
  onSubmit: (payload: ReturnType<typeof buildInsurancePayload>) => void;
  isPending?: boolean;
}

/**
 * Add/edit insurance contract modal (افزودن/ویرایش بیمه). Presentational: owns form
 * state, emits the built payload via onSubmit. Fields mirror the Figma "افزودن بیمه"
 * modal plus the injected coverage/franchise/ceiling controls.
 */
export default function InsuranceModal({ open, editContract, options, kind, onClose, onSubmit, isPending }: Props) {
  const [form, setForm] = useState<InsuranceFormValues>(EMPTY_FORM);

  useEffect(() => {
    if (!open) return;
    setForm(editContract ? contractToForm(editContract) : { ...EMPTY_FORM, kind });
  }, [open, editContract, kind]);

  const set = (patch: Partial<InsuranceFormValues>) => setForm((f) => ({ ...f, ...patch }));
  const isEdit = editContract !== null;

  const submit = () => {
    if (!form.insuranceId) return;
    onSubmit(buildInsurancePayload(form));
  };

  const field = { display: 'flex', flexDirection: 'column' as const, gap: 6 };
  const label = { fontSize: 12, fontWeight: 600, color: 'var(--text-2)' };

  return (
    <Modal
      open={open}
      title={isEdit ? 'ویرایش بیمه' : 'افزودن بیمه'}
      size="md"
      onClose={onClose}
      footer={
        <>
          <button type="button" className="btn ghost" onClick={onClose}>لغو</button>
          <button
            type="button"
            className="btn primary"
            disabled={!form.insuranceId || isPending}
            onClick={submit}
          >
            {isPending ? '...' : 'ثبت بیمه'}
          </button>
        </>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={field}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
            <label style={label}>نام بیمه</label>
            <span style={{
              fontSize: 11, fontWeight: 600, padding: '2px 10px', borderRadius: 'var(--r-pill)',
              background: 'var(--primary-soft)', color: 'var(--primary)',
            }}>
              {KIND_LABEL[form.kind] ?? form.kind}
            </span>
          </div>
          <SearchableSelect
            options={options.map((i) => ({ value: String(i.insurance_id), label: i.insurance_name }))}
            value={form.insuranceId}
            onChange={(v) => set({ insuranceId: v ? String(v) : '' })}
            isDisabled={isEdit}
            placeholder="انتخاب کنید..."
          />
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div style={field}>
            <label style={label}>تاریخ شروع قرارداد</label>
            <PersianDateInput value={form.effectiveFrom} onChange={(v) => set({ effectiveFrom: v })} placeholder="انتخاب" />
          </div>
          <div style={field}>
            <label style={label}>تاریخ پایان قرارداد</label>
            <PersianDateInput value={form.effectiveTo} onChange={(v) => set({ effectiveTo: v })} placeholder="انتخاب" />
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
          <div style={field}>
            <label style={label}>درصد پوشش</label>
            <input type="text" inputMode="numeric" dir="ltr" className="input" value={form.coverage} onChange={(e) => set({ coverage: digitsOnly(e.target.value, 3) })} />
          </div>
          <div style={field}>
            <label style={label}>فرانشیز (تومان)</label>
            <input type="text" inputMode="numeric" dir="ltr" className="input" value={form.franchise} onChange={(e) => set({ franchise: digitsOnly(e.target.value) })} />
          </div>
          <div style={field}>
            <label style={label}>سقف تعهد (تومان)</label>
            <input type="text" inputMode="numeric" dir="ltr" className="input" placeholder="بی‌نهایت" value={form.ceiling} onChange={(e) => set({ ceiling: digitsOnly(e.target.value) })} />
          </div>
        </div>
      </div>
    </Modal>
  );
}
