import { useForm } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useState } from 'react';
import type { FormEvent } from 'react';
import EmployeeCompensationController from '@/actions/App/Http/Controllers/Admin/EmployeeCompensationController';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { formatCurrency, formatDate } from '@/lib/utils';

type Option = { value: string; label: string };

export type EmployeeCompensationData = {
    id: number;
    effective_date: string;
    base_salary: number;
    payment_method: string;
    payment_method_label: string;
    mobile_money_provider: string | null;
    payment_account_number: string | null;
    bank_name: string | null;
    note: string | null;
    items: Array<{
        id: number;
        type: string;
        type_label: string;
        label: string;
        amount: number;
        is_taxable: boolean;
        is_subject_to_cnps: boolean;
    }>;
};

type ItemDraft = {
    type: string;
    label: string;
    amount: string;
    is_taxable: boolean;
    is_subject_to_cnps: boolean;
};

export function EmployeeCompensationSection({
    employeeId,
    compensations,
    paymentMethods,
    itemTypes,
    canView,
    canUpdate,
}: {
    employeeId: number;
    compensations: EmployeeCompensationData[];
    paymentMethods: Option[];
    itemTypes: Option[];
    canView: boolean;
    canUpdate: boolean;
}) {
    const [open, setOpen] = useState(false);
    const form = useForm({
        effective_date: '',
        base_salary: '',
        payment_method: paymentMethods[0]?.value ?? 'bank_transfer',
        mobile_money_provider: '',
        payment_account_number: '',
        bank_name: '',
        note: '',
        items: [] as ItemDraft[],
    });

    if (!canView) {
        return null;
    }

    function submit(event: FormEvent) {
        event.preventDefault();
        form.transform((data) => ({
            ...data,
            base_salary: Number(data.base_salary),
            mobile_money_provider: data.mobile_money_provider || null,
            payment_account_number: data.payment_account_number || null,
            bank_name: data.bank_name || null,
            note: data.note || null,
            items: data.items.map((item) => ({
                ...item,
                amount: Number(item.amount),
            })),
        }));
        form.post(EmployeeCompensationController.store.url(employeeId), {
            preserveScroll: true,
            onSuccess: () => {
                setOpen(false);
                form.reset();
            },
        });
    }

    const current = compensations[0] ?? null;

    return (
        <section className="space-y-4">
            <div className="flex items-center justify-between">
                <h2 className="text-lg font-semibold tracking-tight">Rémunération</h2>
                {canUpdate && (
                    <Button type="button" variant="outline" size="sm" onClick={() => setOpen((value) => !value)}>
                        <Plus className="size-4" />
                        Nouvelle rémunération
                    </Button>
                )}
            </div>
            <p className="text-sm text-muted-foreground">
                Historique versionné : une nouvelle ligne n'écrase jamais les précédentes.
            </p>

            {current ? (
                <div className="rounded-lg border p-4 text-sm">
                    <p className="font-medium">En vigueur depuis le {formatDate(current.effective_date)}</p>
                    <p>Salaire de base : {formatCurrency(current.base_salary)}</p>
                    <p>Paiement : {current.payment_method_label}</p>
                </div>
            ) : (
                <p className="text-sm text-muted-foreground">Aucune rémunération saisie.</p>
            )}

            {open && canUpdate && (
                <form onSubmit={submit} className="grid gap-3 rounded-lg border p-4 md:grid-cols-2">
                    <div className="space-y-1">
                        <Label>Date d'effet</Label>
                        <Input
                            type="date"
                            value={form.data.effective_date}
                            onChange={(event) => form.setData('effective_date', event.target.value)}
                        />
                        <InputError message={form.errors.effective_date} />
                    </div>
                    <div className="space-y-1">
                        <Label>Salaire de base</Label>
                        <Input
                            value={form.data.base_salary}
                            onChange={(event) => form.setData('base_salary', event.target.value)}
                        />
                        <InputError message={form.errors.base_salary} />
                    </div>
                    <div className="space-y-1">
                        <Label>Mode de paiement</Label>
                        <Select
                            value={form.data.payment_method}
                            onValueChange={(value) => form.setData('payment_method', value)}
                        >
                            <SelectTrigger>
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                                {paymentMethods.map((method) => (
                                    <SelectItem key={method.value} value={method.value}>
                                        {method.label}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>
                    {form.data.payment_method === 'mobile_money' && (
                        <div className="space-y-1">
                            <Label>Fournisseur mobile money</Label>
                            <Input
                                placeholder="Orange Money, MTN Money, Wave…"
                                value={form.data.mobile_money_provider}
                                onChange={(event) => form.setData('mobile_money_provider', event.target.value)}
                            />
                            <InputError message={form.errors.mobile_money_provider} />
                        </div>
                    )}
                    <div className="space-y-1">
                        <Label>N° de compte / mobile money</Label>
                        <Input
                            value={form.data.payment_account_number}
                            onChange={(event) => form.setData('payment_account_number', event.target.value)}
                        />
                    </div>
                    <div className="space-y-1">
                        <Label>Banque</Label>
                        <Input
                            value={form.data.bank_name}
                            onChange={(event) => form.setData('bank_name', event.target.value)}
                        />
                    </div>
                    {form.data.items.map((item, index) => (
                        <div key={index} className="md:col-span-2 grid gap-2 rounded-md border p-3 md:grid-cols-4">
                            <Select
                                value={item.type}
                                onValueChange={(value) => {
                                    const items = [...form.data.items];
                                    items[index] = { ...items[index], type: value };
                                    form.setData('items', items);
                                }}
                            >
                                <SelectTrigger>
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    {itemTypes.map((type) => (
                                        <SelectItem key={type.value} value={type.value}>
                                            {type.label}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <Input
                                placeholder="Libellé"
                                value={item.label}
                                onChange={(event) => {
                                    const items = [...form.data.items];
                                    items[index] = { ...items[index], label: event.target.value };
                                    form.setData('items', items);
                                }}
                            />
                            <Input
                                placeholder="Montant"
                                value={item.amount}
                                onChange={(event) => {
                                    const items = [...form.data.items];
                                    items[index] = { ...items[index], amount: event.target.value };
                                    form.setData('items', items);
                                }}
                            />
                            <label className="flex items-center gap-2 text-sm">
                                <Checkbox
                                    checked={item.is_taxable}
                                    onCheckedChange={(checked) => {
                                        const items = [...form.data.items];
                                        items[index] = { ...items[index], is_taxable: Boolean(checked) };
                                        form.setData('items', items);
                                    }}
                                />
                                Taxable
                            </label>
                        </div>
                    ))}
                    <div className="md:col-span-2 flex gap-2">
                        <Button
                            type="button"
                            variant="outline"
                            onClick={() =>
                                form.setData('items', [
                                    ...form.data.items,
                                    {
                                        type: itemTypes[0]?.value ?? 'allowance',
                                        label: '',
                                        amount: '',
                                        is_taxable: true,
                                        is_subject_to_cnps: true,
                                    },
                                ])
                            }
                        >
                            Ajouter une prime / indemnité
                        </Button>
                        <Button type="submit" disabled={form.processing}>
                            Enregistrer
                        </Button>
                    </div>
                </form>
            )}

            {compensations.length > 0 && (
                <ol className="space-y-3">
                    {compensations.map((compensation) => (
                        <li key={compensation.id} className="rounded-md border p-3 text-sm">
                            <p className="font-medium">
                                {formatDate(compensation.effective_date)} · {formatCurrency(compensation.base_salary)} · {compensation.payment_method_label}
                            </p>
                            {compensation.items.map((item) => (
                                <p key={item.id} className="text-muted-foreground">
                                    {item.type_label} — {item.label} : {formatCurrency(item.amount)}
                                </p>
                            ))}
                        </li>
                    ))}
                </ol>
            )}
        </section>
    );
}
