import AdminLayout from '@/Layouts/AdminLayout';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { api } from '@/lib/api';
import { Head, router } from '@inertiajs/react';
import { ArrowLeft, Coins, Save } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';

// ── Types ─────────────────────────────────────────────────────────────────────

interface CurrencyForm {
    code: string;
    name: string;
    symbol: string;
    rate: string;
    decimals: string;
    is_enabled: boolean;
    sort_order: string;
}

interface Props {
    currency?: {
        id: string;
        code: string;
        name: string;
        symbol: string;
        rate: number;
        decimals: number;
        is_base: boolean;
        is_enabled: boolean;
        sort_order: number;
    };
}

// ── Helpers ───────────────────────────────────────────────────────────────────

function Field({
    label,
    error,
    hint,
    children,
}: {
    label: string;
    error?: string;
    hint?: string;
    children: React.ReactNode;
}) {
    return (
        <div className="space-y-1.5">
            <label className="text-muted-foreground block text-xs font-semibold tracking-wide uppercase">
                {label}
            </label>
            {children}
            {hint && (
                <p className="text-muted-foreground dark:text-muted-foreground/60 text-[10px]">
                    {hint}
                </p>
            )}
            {error && <p className="text-destructive text-xs">{error}</p>}
        </div>
    );
}

// ── Page ──────────────────────────────────────────────────────────────────────

export default function CurrenciesForm({ currency }: Props) {
    const isEdit = !!currency;
    const isBase = currency?.is_base ?? false;

    const [form, setForm] = useState<CurrencyForm>({
        code: currency?.code ?? '',
        name: currency?.name ?? '',
        symbol: currency?.symbol ?? '',
        rate: String(currency?.rate ?? ''),
        decimals: String(currency?.decimals ?? 2),
        is_enabled: currency?.is_enabled ?? true,
        sort_order: String(currency?.sort_order ?? 0),
    });

    const [errors, setErrors] = useState<Record<string, string>>({});
    const [saving, setSaving] = useState(false);

    const setField = (key: keyof CurrencyForm, value: string | boolean) =>
        setForm((prev) => ({ ...prev, [key]: value }));

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setErrors({});
        setSaving(true);

        const payload = {
            ...form,
            code: form.code.toUpperCase(),
            rate: parseFloat(form.rate) || 0,
            decimals: parseInt(form.decimals) || 0,
            sort_order: parseInt(form.sort_order) || 0,
        };

        try {
            if (isEdit) {
                await api.put(`/admin/currencies/${currency!.id}`, payload);
            } else {
                await api.post('/admin/currencies', payload);
            }
            toast.success(isEdit ? 'Currency updated' : 'Currency created');
            router.visit('/admin/currencies');
        } catch (err) {
            const apiErr = err as {
                errors?: Record<string, string[]>;
                message?: string;
            };
            if (apiErr.errors) {
                const flat: Record<string, string> = {};
                Object.entries(apiErr.errors).forEach(([k, v]) => {
                    flat[k] = Array.isArray(v) ? v[0] : String(v);
                });
                setErrors(flat);
                toast.error('Please fix the errors below.');
            } else {
                toast.error(apiErr.message ?? 'Failed to save currency');
            }
        } finally {
            setSaving(false);
        }
    };

    return (
        <AdminLayout
            title={isEdit ? `Edit: ${currency!.code}` : 'New Currency'}
            breadcrumbs={[
                { label: 'Billing' },
                { label: 'Currencies', href: '/admin/currencies' },
                { label: isEdit ? currency!.code : 'New Currency' },
            ]}
        >
            <Head
                title={
                    isEdit
                        ? `Edit Currency — ${currency!.code}`
                        : 'New Currency'
                }
            />

            <form onSubmit={handleSubmit} className="p-6 lg:p-8">
                <div className="mb-6 flex items-center gap-3">
                    <button
                        type="button"
                        onClick={() => router.visit('/admin/currencies')}
                        aria-label="Back to currencies"
                        className="border-border text-muted-foreground hover:bg-muted/40 hover:text-foreground flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border transition-colors"
                    >
                        <ArrowLeft className="h-4 w-4" />
                    </button>
                    <Coins className="text-primary h-5 w-5" />
                    <h1 className="text-foreground text-lg font-bold">
                        {isEdit ? 'Edit Currency' : 'New Currency'}
                    </h1>
                </div>

                <div className="max-w-xl">
                    <div className="pf-glass space-y-5 rounded-xl p-6">
                        <p className="text-muted-foreground dark:text-muted-foreground/50 text-[10px] font-bold tracking-widest uppercase">
                            Currency details
                        </p>

                        <div className="grid grid-cols-2 gap-3">
                            <Field
                                label="Code"
                                error={errors.code}
                                hint={
                                    isBase
                                        ? 'The base currency code cannot be changed.'
                                        : 'ISO 4217 code, e.g. KES.'
                                }
                            >
                                <Input
                                    value={form.code}
                                    onChange={(e) =>
                                        setField(
                                            'code',
                                            e.target.value.toUpperCase(),
                                        )
                                    }
                                    placeholder="KES"
                                    maxLength={3}
                                    disabled={isBase}
                                    className={isBase ? 'opacity-60' : ''}
                                />
                            </Field>
                            <Field label="Symbol" error={errors.symbol}>
                                <Input
                                    value={form.symbol}
                                    onChange={(e) =>
                                        setField('symbol', e.target.value)
                                    }
                                    placeholder="KSh"
                                    maxLength={8}
                                />
                            </Field>
                        </div>

                        <Field label="Name" error={errors.name}>
                            <Input
                                value={form.name}
                                onChange={(e) =>
                                    setField('name', e.target.value)
                                }
                                placeholder="Kenyan Shilling"
                            />
                        </Field>

                        <Field
                            label="Conversion rate"
                            error={errors.rate}
                            hint={
                                isBase
                                    ? 'The base currency rate is fixed at 1.'
                                    : 'Units of this currency per one unit of the base currency.'
                            }
                        >
                            <Input
                                type="number"
                                min={0}
                                step="any"
                                value={isBase ? '1' : form.rate}
                                onChange={(e) =>
                                    setField('rate', e.target.value)
                                }
                                placeholder="129"
                                disabled={isBase}
                                className={isBase ? 'opacity-60' : ''}
                            />
                        </Field>

                        <div className="grid grid-cols-2 gap-3">
                            <Field
                                label="Decimals"
                                error={errors.decimals}
                                hint="Display precision for converted prices."
                            >
                                <Input
                                    type="number"
                                    min={0}
                                    max={4}
                                    value={form.decimals}
                                    onChange={(e) =>
                                        setField('decimals', e.target.value)
                                    }
                                    placeholder="2"
                                />
                            </Field>
                            <Field label="Sort order" error={errors.sort_order}>
                                <Input
                                    type="number"
                                    min={0}
                                    value={form.sort_order}
                                    onChange={(e) =>
                                        setField('sort_order', e.target.value)
                                    }
                                    placeholder="0"
                                />
                            </Field>
                        </div>

                        <div className="pt-1">
                            <label
                                className={
                                    isBase
                                        ? 'flex cursor-default items-center gap-2.5 opacity-60'
                                        : 'flex cursor-pointer items-center gap-2.5'
                                }
                            >
                                <Checkbox
                                    checked={isBase ? true : form.is_enabled}
                                    disabled={isBase}
                                    onCheckedChange={(v) =>
                                        setField('is_enabled', !!v)
                                    }
                                />
                                <span className="text-foreground text-sm">
                                    Enabled
                                </span>
                            </label>
                            {isBase && (
                                <p className="text-muted-foreground dark:text-muted-foreground/60 mt-1.5 text-[10px]">
                                    The base currency is always enabled.
                                </p>
                            )}
                        </div>
                    </div>

                    <button
                        type="submit"
                        disabled={saving}
                        className="pf-btn pf-btn-primary mt-6 flex w-full items-center justify-center gap-2"
                    >
                        <Save className="h-4 w-4" />
                        {saving
                            ? 'Saving…'
                            : isEdit
                              ? 'Update Currency'
                              : 'Create Currency'}
                    </button>
                </div>
            </form>
        </AdminLayout>
    );
}
