import React, { useEffect, useMemo, useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { PlusIcon, PencilIcon, TrashIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { DiscountRule, DiscountRuleType } from '../types';
import { formatRial, formatDate, tomanToRial, rialToToman, tehranWallClockToUnix } from '../lib/utils';
import Modal from './ui/Modal';
import ConfirmDialog from './ui/ConfirmDialog';
import SearchableSelect from './ui/SearchableSelect';
import PriceInput from './ui/PriceInput';
import PersianDateInput from './ui/PersianDateInput';
import { digitsOnly } from '../lib/utils';
import { usePermissions } from '../hooks/usePermissions';

const TYPE_LABELS: Record<DiscountRuleType, string> = {
  patient_tag:      'تگ بیمار',
  invoice_amount:   'مبلغ فاکتور',
  specific_patient: 'بیمار خاص',
  occasion:         'مناسبتی',
  service:          'سرویس',
  visit_count:      'تعداد مراجعات',
};

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

const unixToIso = (u: number | null): string => {
  if (!u) return '';
  const d = new Date(u * 1000);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
};
const isoToUnix = (iso: string): number | null => (iso ? tehranWallClockToUnix(iso, '00:00') : null);

interface FormState {
  name: string;
  type: DiscountRuleType;
  discount_type: 'percent' | 'fixed';
  value: number;              // percent (0..100) or toman (fixed)
  priority: number;
  combinable: boolean;
  active: boolean;
  valid_from: string;         // iso
  valid_to: string;           // iso
  target_tag_uuid: string;
  target_record_uuid: string;
  target_service_item_uuid: string;
  min_amount_toman: number;
  min_visit_count: number;
  occasion_kind: '' | 'birthday';
}

const emptyForm = (): FormState => ({
  name: '', type: 'invoice_amount', discount_type: 'percent', value: 0, priority: 0,
  combinable: false, active: true, valid_from: '', valid_to: '',
  target_tag_uuid: '', target_record_uuid: '', target_service_item_uuid: '',
  min_amount_toman: 0, min_visit_count: 0, occasion_kind: '',
});

const fromRule = (r: DiscountRule): FormState => ({
  name: r.name, type: r.type, discount_type: r.discount_type,
  value: r.discount_type === 'fixed' ? rialToToman(r.value) : r.value,
  priority: r.priority, combinable: r.combinable, active: r.active,
  valid_from: unixToIso(r.valid_from), valid_to: unixToIso(r.valid_to),
  target_tag_uuid: r.target_tag_uuid ?? '', target_record_uuid: r.target_record_uuid ?? '',
  target_service_item_uuid: r.target_service_item_uuid ?? '',
  min_amount_toman: r.min_amount_rials ? rialToToman(r.min_amount_rials) : 0,
  min_visit_count: r.min_visit_count ?? 0,
  occasion_kind: r.occasion_kind === 'birthday' ? 'birthday' : '',
});

function labelStyle(): React.CSSProperties { return { fontSize: 12.5, color: 'var(--text-3)', display: 'block', marginBottom: 6 }; }

export default function DiscountTab() {
  const qc = useQueryClient();
  // مجوزهای منشی؛ برای owner/پزشک همیشه true (usePermissions بدون context آزاد است).
  const { can } = usePermissions();
  const canCreate = can('discounts', 'create');
  const canUpdate = can('discounts', 'update');
  const canDelete = can('discounts', 'delete');
  const [modal, setModal] = useState<'create' | DiscountRule | null>(null);
  const [toDelete, setToDelete] = useState<DiscountRule | null>(null);

  const { data, isLoading } = useQuery({
    queryKey: ['admin-discount-rules'],
    queryFn: () => api.get<ApiResponse<DiscountRule[]>>('/api/v1/admin/discount-rules'),
  });
  const rules: DiscountRule[] = (data?.data as any)?.data ?? (data?.data as any) ?? [];

  const removeMut = useMutation({
    mutationFn: (uuid: string) => api.delete(`/api/v1/admin/discount-rules/${uuid}`),
    onSuccess: () => { toast.success('قانون حذف شد'); setToDelete(null); qc.invalidateQueries({ queryKey: ['admin-discount-rules'] }); },
    onError: (e: Error) => toast.error(e.message),
  });

  const discountDisplay = (r: DiscountRule) =>
    r.discount_type === 'percent' ? `${r.value}٪` : formatRial(r.value);

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
        <span style={{ fontSize: 13, color: 'var(--text-3)' }}>قوانین تخفیف عمومی — بر اساس تگ، مبلغ، بیمار، مناسبت، سرویس یا تعداد مراجعه</span>
        {canCreate && (
          <button className="btn primary sm" onClick={() => setModal('create')}>
            <PlusIcon style={{ width: 15 }} /> قانون جدید
          </button>
        )}
      </div>

      {isLoading ? (
        <div style={{ padding: 24, color: 'var(--text-3)', fontSize: 13 }}>در حال بارگذاری...</div>
      ) : rules.length === 0 ? (
        <div className="card" style={{ padding: 28, textAlign: 'center', color: 'var(--text-3)', fontSize: 14 }}>هنوز قانونی تعریف نشده است.</div>
      ) : (
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--surface-2)', textAlign: 'right' }}>
                <th style={{ padding: 10 }}>نام</th>
                <th style={{ padding: 10 }}>نوع</th>
                <th style={{ padding: 10 }}>تخفیف</th>
                <th style={{ padding: 10 }}>اولویت</th>
                <th style={{ padding: 10 }}>ترکیب‌پذیر</th>
                <th style={{ padding: 10 }}>وضعیت</th>
                <th style={{ padding: 10 }}></th>
              </tr>
            </thead>
            <tbody>
              {rules.map((r) => (
                <tr key={r.uuid} style={{ borderTop: '1px solid var(--border)' }}>
                  <td style={{ padding: 10 }}>{r.name}</td>
                  <td style={{ padding: 10 }}>{TYPE_LABELS[r.type]}</td>
                  <td style={{ padding: 10 }}>{discountDisplay(r)}</td>
                  <td style={{ padding: 10 }}>{r.priority}</td>
                  <td style={{ padding: 10 }}>{r.combinable ? 'بله' : 'خیر'}</td>
                  <td style={{ padding: 10 }}>
                    <span className={`badge ${r.active ? 'green' : ''}`}>{r.active ? 'فعال' : 'غیرفعال'}</span>
                  </td>
                  <td style={{ padding: 10, textAlign: 'left', whiteSpace: 'nowrap' }}>
                    {canUpdate && (
                      <button className="mini-btn" onClick={() => setModal(r)} aria-label="ویرایش"><PencilIcon style={{ width: 15 }} /></button>
                    )}
                    {canDelete && (
                      <button className="mini-btn" onClick={() => setToDelete(r)} aria-label="حذف"><TrashIcon style={{ width: 15 }} /></button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {modal && (
        <RuleModal
          initial={modal === 'create' ? null : modal}
          onClose={() => setModal(null)}
          onSaved={() => { setModal(null); qc.invalidateQueries({ queryKey: ['admin-discount-rules'] }); }}
        />
      )}

      <ConfirmDialog
        open={!!toDelete}
        title="حذف قانون تخفیف"
        message={`آیا از حذف «${toDelete?.name}» مطمئن هستید؟`}
        confirmLabel="حذف"
        danger
        loading={removeMut.isPending}
        onConfirm={() => toDelete && removeMut.mutate(toDelete.uuid)}
        onCancel={() => setToDelete(null)}
      />
    </div>
  );
}

function RuleModal({ initial, onClose, onSaved }: { initial: DiscountRule | null; onClose: () => void; onSaved: () => void }) {
  const [f, setF] = useState<FormState>(initial ? fromRule(initial) : emptyForm());
  const set = <K extends keyof FormState>(k: K, v: FormState[K]) => setF((s) => ({ ...s, [k]: v }));

  const tagsQ = useQuery({
    queryKey: ['tenant-tags'], queryFn: () => api.get<ApiResponse<Option[]>>('/api/v1/tenant-tags'),
    enabled: f.type === 'patient_tag',
  });
  const sectionsQ = useQuery({
    queryKey: ['service-sections'], queryFn: () => api.get<ApiResponse<Option[]>>('/api/v1/service-sections'),
    enabled: f.type === 'service',
  });
  const [sectionUuid, setSectionUuid] = useState('');
  const itemsQ = useQuery({
    queryKey: ['service-items', sectionUuid], queryFn: () => api.get<ApiResponse<Option[]>>(`/api/v1/service-items/${sectionUuid}`),
    enabled: f.type === 'service' && !!sectionUuid,
  });
  const tags = (tagsQ.data?.data as any)?.data ?? (tagsQ.data?.data as any) ?? [];
  const sections = (sectionsQ.data?.data as any)?.data ?? (sectionsQ.data?.data as any) ?? [];
  const items = (itemsQ.data?.data as any)?.data ?? (itemsQ.data?.data as any) ?? [];

  const save = useMutation({
    mutationFn: () => {
      const body: Record<string, unknown> = {
        name: f.name.trim(),
        type: f.type,
        discount_type: f.discount_type,
        value: f.discount_type === 'fixed' ? tomanToRial(f.value) : f.value,
        priority: f.priority,
        combinable: f.combinable,
        active: f.active,
        valid_from: isoToUnix(f.valid_from),
        valid_to: isoToUnix(f.valid_to),
        target_tag_uuid: f.type === 'patient_tag' ? (f.target_tag_uuid || null) : null,
        target_record_uuid: f.type === 'specific_patient' ? (f.target_record_uuid.trim() || null) : null,
        target_service_item_uuid: f.type === 'service' ? (f.target_service_item_uuid || null) : null,
        min_amount_rials: f.type === 'invoice_amount' ? tomanToRial(f.min_amount_toman) : null,
        min_visit_count: f.type === 'visit_count' ? f.min_visit_count : null,
        occasion_kind: f.type === 'occasion' ? (f.occasion_kind || null) : null,
      };
      return initial
        ? api.patch(`/api/v1/admin/discount-rules/${initial.uuid}`, body)
        : api.post('/api/v1/admin/discount-rules', body);
    },
    onSuccess: () => { toast.success('قانون ذخیره شد'); onSaved(); },
    onError: (e: Error) => toast.error(e.message),
  });

  const canSave = f.name.trim().length > 0 && f.value >= 0;

  return (
    <Modal open title={initial ? 'ویرایش قانون تخفیف' : 'قانون تخفیف جدید'} onClose={onClose}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div>
          <label style={labelStyle()}>نام قانون</label>
          <input className="cp-input" value={f.name} onChange={(e) => set('name', e.target.value)} placeholder="مثال: بیماران VIP" />
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>
            <label style={labelStyle()}>نوع قانون</label>
            <SearchableSelect
              options={(Object.keys(TYPE_LABELS) as DiscountRuleType[]).map((t) => ({ value: t, label: TYPE_LABELS[t] }))}
              value={f.type} onChange={(v) => set('type', (v as DiscountRuleType) || 'invoice_amount')} height={38}
            />
          </div>
          <div>
            <label style={labelStyle()}>نوع تخفیف</label>
            <SearchableSelect
              options={[{ value: 'percent', label: 'درصدی' }, { value: 'fixed', label: 'مبلغ ثابت' }]}
              value={f.discount_type} onChange={(v) => set('discount_type', (v as 'percent' | 'fixed') || 'percent')} height={38}
            />
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>
            <label style={labelStyle()}>{f.discount_type === 'percent' ? 'درصد تخفیف (۰ تا ۱۰۰)' : 'مبلغ تخفیف (تومان)'}</label>
            {f.discount_type === 'percent'
              ? <input className="cp-input" style={{ width: '100%' }} type="text" inputMode="numeric" dir="ltr" value={f.value} onChange={(e) => set('value', Number(digitsOnly(e.target.value, 3)) || 0)} />
              : <PriceInput className="cp-input" style={{ width: '100%' }} value={f.value} onChange={(v) => set('value', v)} />}
          </div>
          <div>
            <label style={labelStyle()}>اولویت (بزرگ‌تر = مهم‌تر)</label>
            <input className="cp-input" type="text" inputMode="numeric" dir="ltr" value={f.priority} onChange={(e) => set('priority', Number(digitsOnly(e.target.value)) || 0)} />
          </div>
        </div>

        {/* target فیلد پویا بر اساس نوع */}
        {f.type === 'patient_tag' && (
          <div>
            <label style={labelStyle()}>تگ بیمار</label>
            <SearchableSelect
              options={tags.map((t: Option) => ({ value: t.uuid, label: t.name ?? '' }))}
              value={f.target_tag_uuid || null} onChange={(v) => set('target_tag_uuid', v ? String(v) : '')}
              placeholder="انتخاب تگ" isLoading={tagsQ.isLoading} isClearable height={38}
            />
          </div>
        )}
        {f.type === 'invoice_amount' && (
          <div>
            <label style={labelStyle()}>حداقل مبلغ فاکتور (تومان)</label>
            <PriceInput className="cp-input" style={{ width: '100%' }} value={f.min_amount_toman} onChange={(v) => set('min_amount_toman', v)} />
          </div>
        )}
        {f.type === 'specific_patient' && (
          <div>
            <label style={labelStyle()}>شناسه‌ی پرونده‌ی بیمار (uuid)</label>
            <input className="cp-input" dir="ltr" value={f.target_record_uuid} onChange={(e) => set('target_record_uuid', e.target.value)} placeholder="record uuid" />
          </div>
        )}
        {f.type === 'service' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div>
              <label style={labelStyle()}>بخش</label>
              <SearchableSelect
                options={sections.map((s: Option) => ({ value: s.uuid, label: s.name ?? '' }))}
                value={sectionUuid || null} onChange={(v) => { setSectionUuid(v ? String(v) : ''); set('target_service_item_uuid', ''); }}
                placeholder="انتخاب بخش" isLoading={sectionsQ.isLoading} isClearable height={38}
              />
            </div>
            <div>
              <label style={labelStyle()}>سرویس</label>
              <SearchableSelect
                options={items.map((s: Option) => ({ value: s.uuid, label: s.name ?? '' }))}
                value={f.target_service_item_uuid || null} onChange={(v) => set('target_service_item_uuid', v ? String(v) : '')}
                placeholder="انتخاب سرویس" isDisabled={!sectionUuid} isLoading={itemsQ.isLoading} isClearable height={38}
              />
            </div>
          </div>
        )}
        {f.type === 'visit_count' && (
          <div>
            <label style={labelStyle()}>حداقل تعداد مراجعه</label>
            <input className="cp-input" type="text" inputMode="numeric" dir="ltr" value={f.min_visit_count} onChange={(e) => set('min_visit_count', Number(digitsOnly(e.target.value)) || 0)} />
          </div>
        )}
        {f.type === 'occasion' && (
          <div>
            <label style={labelStyle()}>زیرنوع مناسبت</label>
            <SearchableSelect
              options={[{ value: '', label: 'بازه‌ی زمانی' }, { value: 'birthday', label: 'تولد بیمار' }]}
              value={f.occasion_kind} onChange={(v) => set('occasion_kind', (v as '' | 'birthday'))} height={38}
            />
          </div>
        )}

        {/* بازه‌ی اعتبار (اختیاری؛ برای مناسبتی/موقت) */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>
            <label style={labelStyle()}>اعتبار از (اختیاری)</label>
            <PersianDateInput value={f.valid_from} onChange={(v) => set('valid_from', v)} />
          </div>
          <div>
            <label style={labelStyle()}>اعتبار تا (اختیاری)</label>
            <PersianDateInput value={f.valid_to} onChange={(v) => set('valid_to', v)} />
          </div>
        </div>

        <div style={{ display: 'flex', gap: 20, marginTop: 4 }}>
          <label style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13, cursor: 'pointer' }}>
            <input type="checkbox" checked={f.combinable} onChange={(e) => set('combinable', e.target.checked)} /> قابل ترکیب با سایر تخفیف‌ها
          </label>
          <label style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13, cursor: 'pointer' }}>
            <input type="checkbox" checked={f.active} onChange={(e) => set('active', e.target.checked)} /> فعال
          </label>
        </div>

        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 8 }}>
          <button className="btn ghost sm" onClick={onClose}>انصراف</button>
          <button className="btn primary sm" disabled={!canSave || save.isPending} onClick={() => save.mutate()}>
            {save.isPending ? 'در حال ذخیره...' : 'ذخیره'}
          </button>
        </div>
      </div>
    </Modal>
  );
}
