import { useEffect, useMemo, useState } from 'react';
import { IconCheck, IconFileInvoice, IconLayoutGrid, IconX } from '@tabler/icons-react';
import { notifications } from '@/lib/notifications';
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';
import { useAuthStore } from '../../store/authStore';
import { useTranslation } from '../../i18n/hooks/useTranslation';
import { INVOICE_TEMPLATES, DEFAULT_INVOICE_TEMPLATE, SAMPLE_INVOICE, paperPx } from '../../lib/invoiceTemplates';
import InvoicePreviewFrame from './InvoicePreviewFrame';

/**
 * InvoiceTemplatePicker — Settings card (আয় ব্যয় হিসেব tab). Shows the currently
 * chosen invoice template and a button that opens a modal with live previews of
 * every template. Picking a card only stages a selection in-view; the choice is
 * committed to `user.settings.invoiceTemplate` only when "প্রয়োগ করুন" (Apply)
 * is pressed.
 */
export default function InvoiceTemplatePicker() {
    const { t, currentLanguage } = useTranslation();
    const lang = currentLanguage === 'en' ? 'en' : 'bn';
    const tplName = (tpl) => (lang === 'en' ? (tpl?.nameEn || tpl?.name) : tpl?.name);
    const user = useAuthStore((s) => s.user);
    const updateSettings = useAuthStore((s) => s.updateSettings);
    const selected = user?.settings?.invoiceTemplate || DEFAULT_INVOICE_TEMPLATE;
    const [open, setOpen] = useState(false);
    const [pendingId, setPendingId] = useState(selected);
    const [saving, setSaving] = useState(false);

    const selectedName = tplName(INVOICE_TEMPLATES.find((x) => x.id === selected) || INVOICE_TEMPLATES[0]);

    // Each time the modal opens, start the staged selection from the saved one.
    useEffect(() => {
        if (open) setPendingId(selected);
    }, [open, selected]);

    // Build each template's preview HTML once from the shared sample data.
    const previews = useMemo(
        () => INVOICE_TEMPLATES.map((tpl) => ({ ...tpl, html: tpl.build(SAMPLE_INVOICE) })),
        []
    );

    const dirty = pendingId !== selected;

    const apply = async () => {
        if (saving) return;
        if (!dirty) { setOpen(false); return; }
        setSaving(true);
        try {
            await updateSettings({ invoiceTemplate: pendingId });
            notifications.show({ title: t('common.success'), message: t('profile.settingsSaved'), color: 'green' });
            setOpen(false);
        } catch (err) {
            notifications.show({ title: t('common.error'), message: err.message, color: 'red' });
        } finally {
            setSaving(false);
        }
    };

    return (
        <div className="bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-700 shadow-sm p-[22px]">
            <div className="flex items-center gap-2">
                <IconFileInvoice size={18} className="text-primary" />
                <div className="text-[17px] font-semibold text-zinc-800 dark:text-zinc-100">{t('invoiceTemplate.title')}</div>
            </div>
            <div className="text-[13px] text-zinc-500 dark:text-zinc-400 mt-1 mb-4">
                {t('invoiceTemplate.desc')}
            </div>

            <div className="flex items-center gap-3 flex-wrap">
                <div className="text-sm text-zinc-600 dark:text-zinc-400">
                    {t('invoiceTemplate.current')}{' '}
                    <span className="font-semibold text-zinc-900 dark:text-zinc-100">{selectedName}</span>
                </div>
                <button
                    type="button"
                    onClick={() => setOpen(true)}
                    className="ml-auto inline-flex items-center gap-1.5 px-4 py-2 bg-primary hover:bg-primary/90 text-white text-sm font-semibold rounded-lg transition-colors"
                >
                    <IconLayoutGrid size={16} />
                    {t('invoiceTemplate.choose')}
                </button>
            </div>

            {/* Selection modal */}
            <Dialog open={open} onOpenChange={setOpen}>
                <DialogContent
                    showClose={false}
                    overlayClassName="z-[100]"
                    className="p-0 overflow-hidden flex flex-col z-[100]"
                    style={{ width: '1160px', maxWidth: '96vw', maxHeight: '92vh' }}
                >
                    {/* Header */}
                    <div className="flex items-center justify-between gap-4 px-6 py-4 border-b border-zinc-100 dark:border-zinc-800">
                        <DialogTitle className="text-base font-semibold text-zinc-800 dark:text-zinc-100">
                            {t('invoiceTemplate.chooseTitle')}
                        </DialogTitle>
                        <button
                            type="button"
                            onClick={() => setOpen(false)}
                            aria-label={t('common.close') || 'বন্ধ'}
                            className="inline-flex h-9 w-9 flex-none items-center justify-center rounded-lg bg-red-500 text-white hover:bg-red-600 transition-colors"
                        >
                            <IconX size={18} />
                        </button>
                    </div>

                    {/* Body */}
                    <div className="p-6 overflow-y-auto">
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
                            {previews.map((tpl) => {
                                const isSel = pendingId === tpl.id;
                                const isCurrent = selected === tpl.id;
                                return (
                                    <button
                                        key={tpl.id}
                                        type="button"
                                        onClick={() => setPendingId(tpl.id)}
                                        className={`group relative flex flex-col rounded-xl border-2 p-2 text-left transition ${
                                            isSel
                                                ? 'border-primary ring-2 ring-primary/30 bg-primary/5'
                                                : 'border-zinc-200 dark:border-zinc-700 hover:border-primary/50'
                                        }`}
                                    >
                                        {/* Fixed height + fit-page scale so the whole invoice is always visible. */}
                                        <div className="h-[300px] overflow-hidden rounded-lg ring-1 ring-black/5 dark:ring-white/10 bg-zinc-100 dark:bg-zinc-800 py-2 pointer-events-none">
                                            <InvoicePreviewFrame
                                                html={tpl.html}
                                                debounceMs={0}
                                                paper={paperPx(tpl.id === '1f' ? 'slip' : 'a4')}
                                                fitHeight={284}
                                            />
                                        </div>
                                        <div className="mt-2 flex items-center justify-between gap-2 px-0.5">
                                            <span className={`text-sm font-semibold ${isSel ? 'text-primary' : 'text-zinc-700 dark:text-zinc-300'}`}>
                                                {tplName(tpl)}
                                                {isCurrent && (
                                                    <span className="ml-1.5 text-[10.5px] font-medium text-zinc-400 dark:text-zinc-500">
                                                        {t('invoiceTemplate.currentTag')}
                                                    </span>
                                                )}
                                            </span>
                                            {isSel && (
                                                <span className="inline-flex items-center gap-1 text-[11px] font-bold text-primary">
                                                    <IconCheck size={14} /> {t('invoiceTemplate.selected')}
                                                </span>
                                            )}
                                        </div>
                                    </button>
                                );
                            })}
                        </div>
                    </div>

                    {/* Footer — apply the staged selection */}
                    <div className="flex items-center justify-end gap-2.5 px-6 py-4 border-t border-zinc-100 dark:border-zinc-800 bg-zinc-50 dark:bg-zinc-900/40">
                        <button
                            type="button"
                            onClick={() => setOpen(false)}
                            className="px-4 py-2 text-sm font-semibold rounded-lg border border-zinc-200 dark:border-zinc-700 text-zinc-600 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
                        >
                            {t('common.cancel')}
                        </button>
                        <button
                            type="button"
                            onClick={apply}
                            disabled={saving || !dirty}
                            className="inline-flex items-center gap-1.5 px-5 py-2 bg-primary hover:bg-primary/90 text-white text-sm font-semibold rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            {saving ? (
                                <span className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                            ) : (
                                <IconCheck size={16} />
                            )}
                            {t('invoiceTemplate.apply')}
                        </button>
                    </div>
                </DialogContent>
            </Dialog>
        </div>
    );
}
