import { router, useForm } from '@inertiajs/react';
import { Download, Plus, Trash2 } from 'lucide-react';
import { useState, type FormEvent } from 'react';
import EmployeeController from '@/actions/App/Http/Controllers/Admin/EmployeeController';
import { ConfirmDialog } from '@/components/confirm-dialog';
import InputError from '@/components/input-error';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { formatDate } from '@/lib/utils';
import type { ContractTypeOption } from './employee-form';

export type EmployeeContractData = {
    id: number;
    type: string;
    type_label: string;
    start_date: string;
    end_date: string | null;
    job_title: string | null;
    notes: string | null;
    is_current: boolean;
    has_document: boolean;
    document_original_name: string | null;
    amendments: Array<{
        id: number;
        effective_date: string;
        title: string;
        description: string | null;
        has_document: boolean;
        document_original_name: string | null;
        created_by: { id: number; name: string } | null;
        created_at: string | null;
    }>;
};

type Props = {
    employeeId: number;
    currentContract: EmployeeContractData | null;
    contracts: EmployeeContractData[];
    contractTypes: ContractTypeOption[];
    canUpdate: boolean;
};

export function EmployeeContractsSection({
    employeeId,
    currentContract,
    contracts,
    contractTypes,
    canUpdate,
}: Props) {
    const [contractOpen, setContractOpen] = useState(false);
    const [editingContractId, setEditingContractId] = useState<number | null>(
        null,
    );
    const [amendmentContractId, setAmendmentContractId] = useState<
        number | null
    >(null);
    const [expandedId, setExpandedId] = useState<number | null>(
        currentContract?.id ?? contracts[0]?.id ?? null,
    );

    const contractForm = useForm({
        type: contractTypes[0]?.value ?? 'cdi',
        start_date: '',
        end_date: '',
        job_title: '',
        notes: '',
        is_current: true,
        document: null as File | null,
    });

    const amendmentForm = useForm({
        effective_date: '',
        title: '',
        description: '',
        document: null as File | null,
    });

    function closeContractModal() {
        setContractOpen(false);
        setEditingContractId(null);
        contractForm.reset();
        contractForm.clearErrors();
    }

    function openCreateContract() {
        setEditingContractId(null);
        contractForm.setData({
            type: contractTypes[0]?.value ?? 'cdi',
            start_date: '',
            end_date: '',
            job_title: '',
            notes: '',
            is_current: true,
            document: null,
        });
        contractForm.clearErrors();
        setContractOpen(true);
    }

    function openEditContract(contract: EmployeeContractData) {
        setEditingContractId(contract.id);
        contractForm.setData({
            type: contract.type,
            start_date: contract.start_date,
            end_date: contract.end_date ?? '',
            job_title: contract.job_title ?? '',
            notes: contract.notes ?? '',
            is_current: contract.is_current,
            document: null,
        });
        contractForm.clearErrors();
        setContractOpen(true);
        setExpandedId(contract.id);
    }

    function submitContract(event: FormEvent) {
        event.preventDefault();

        const options = {
            forceFormData: true,
            preserveScroll: true,
            onSuccess: () => closeContractModal(),
        };

        contractForm.transform(() => ({
            type: contractForm.data.type,
            start_date: contractForm.data.start_date,
            end_date: contractForm.data.end_date || null,
            job_title: contractForm.data.job_title || null,
            notes: contractForm.data.notes || null,
            is_current: contractForm.data.is_current,
            document: contractForm.data.document,
        }));

        if (editingContractId) {
            contractForm.put(
                EmployeeController.updateContract.url({
                    employee: employeeId,
                    contract: editingContractId,
                }),
                options,
            );

            return;
        }

        contractForm.post(
            EmployeeController.storeContract.url(employeeId),
            options,
        );
    }

    function submitAmendment(event: FormEvent) {
        event.preventDefault();
        if (!amendmentContractId) {
            return;
        }

        amendmentForm.transform(() => ({
            effective_date: amendmentForm.data.effective_date,
            title: amendmentForm.data.title,
            description: amendmentForm.data.description || null,
            document: amendmentForm.data.document,
        }));

        amendmentForm.post(
            EmployeeController.storeAmendment.url({
                employee: employeeId,
                contract: amendmentContractId,
            }),
            {
                forceFormData: true,
                preserveScroll: true,
                onSuccess: () => {
                    setAmendmentContractId(null);
                    amendmentForm.reset();
                },
            },
        );
    }

    return (
        <div className="space-y-10">
            <section className="border-border space-y-6 border-t pt-10">
                <div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
                    <div className="space-y-1.5">
                        <p className="text-muted-foreground text-xs font-medium tracking-[0.14em] uppercase">
                            Dossier
                        </p>
                        <h2 className="text-lg font-semibold tracking-tight">
                            Contrat actuel
                        </h2>
                        <p className="text-muted-foreground max-w-xl text-sm leading-relaxed">
                            Contrat courant synchronisé avec la fiche
                            collaborateur.
                        </p>
                    </div>
                    {canUpdate && (
                        <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={openCreateContract}
                        >
                            <Plus />
                            Nouveau contrat
                        </Button>
                    )}
                </div>

                {currentContract ? (
                    <div className="space-y-5">
                        <dl className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
                            <div className="space-y-1">
                                <dt className="text-muted-foreground text-xs tracking-wide uppercase">
                                    Type
                                </dt>
                                <dd className="text-sm font-medium tracking-tight">
                                    {currentContract.type_label}
                                </dd>
                            </div>
                            <div className="space-y-1">
                                <dt className="text-muted-foreground text-xs tracking-wide uppercase">
                                    Période
                                </dt>
                                <dd className="text-sm font-medium tracking-tight">
                                    {formatDate(currentContract.start_date)}
                                    {' → '}
                                    {currentContract.end_date
                                        ? formatDate(currentContract.end_date)
                                        : 'En cours'}
                                </dd>
                            </div>
                            <div className="space-y-1">
                                <dt className="text-muted-foreground text-xs tracking-wide uppercase">
                                    Poste
                                </dt>
                                <dd className="text-sm font-medium tracking-tight">
                                    {currentContract.job_title || '—'}
                                </dd>
                            </div>
                            <div className="space-y-1">
                                <dt className="text-muted-foreground text-xs tracking-wide uppercase">
                                    Document
                                </dt>
                                <dd className="text-sm font-medium tracking-tight">
                                    {currentContract.has_document
                                        ? currentContract.document_original_name ||
                                          'Fichier joint'
                                        : 'Aucun'}
                                </dd>
                            </div>
                        </dl>

                        {canUpdate && (
                            <div className="flex flex-wrap gap-2">
                                {currentContract.has_document && (
                                    <Button variant="outline" size="sm" asChild>
                                        <a
                                            href={EmployeeController.downloadContract.url(
                                                {
                                                    employee: employeeId,
                                                    contract:
                                                        currentContract.id,
                                                },
                                            )}
                                        >
                                            <Download />
                                            Télécharger
                                        </a>
                                    </Button>
                                )}
                                <Button
                                    type="button"
                                    variant="outline"
                                    size="sm"
                                    onClick={() =>
                                        openEditContract(currentContract)
                                    }
                                >
                                    Modifier
                                </Button>
                                <ConfirmDialog
                                    trigger={
                                        <Button
                                            type="button"
                                            variant="ghost"
                                            size="sm"
                                        >
                                            Clôturer
                                        </Button>
                                    }
                                    title="Clôturer ce contrat ?"
                                    description="Le contrat ne sera plus le contrat courant."
                                    confirmLabel="Clôturer"
                                    onConfirm={() =>
                                        router.post(
                                            EmployeeController.endContract.url({
                                                employee: employeeId,
                                                contract: currentContract.id,
                                            }),
                                            {
                                                end_date: new Date()
                                                    .toISOString()
                                                    .slice(0, 10),
                                            },
                                            { preserveScroll: true },
                                        )
                                    }
                                />
                            </div>
                        )}
                    </div>
                ) : (
                    <p className="text-muted-foreground text-sm">
                        Aucun contrat courant.
                    </p>
                )}
            </section>

            <Dialog
                open={contractOpen && canUpdate}
                onOpenChange={(open) => {
                    if (!open) {
                        closeContractModal();
                    }
                }}
            >
                <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">
                    <DialogHeader>
                        <DialogTitle>
                            {editingContractId
                                ? 'Modifier le contrat'
                                : 'Nouveau contrat'}
                        </DialogTitle>
                        <DialogDescription>
                            {editingContractId
                                ? 'Mettre à jour les informations du contrat.'
                                : 'Le nouveau contrat pourra devenir le contrat courant.'}
                        </DialogDescription>
                    </DialogHeader>

                    <form onSubmit={submitContract} className="space-y-4">
                        <div className="grid gap-4 sm:grid-cols-2">
                            <div className="grid gap-2">
                                <Label>Type</Label>
                                <Select
                                    value={contractForm.data.type}
                                    onValueChange={(value) =>
                                        contractForm.setData('type', value)
                                    }
                                >
                                    <SelectTrigger>
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {contractTypes.map((type) => (
                                            <SelectItem
                                                key={type.value}
                                                value={type.value}
                                            >
                                                {type.label}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                <InputError
                                    message={contractForm.errors.type}
                                />
                            </div>
                            <div className="grid gap-2">
                                <Label>Poste</Label>
                                <Input
                                    value={contractForm.data.job_title}
                                    onChange={(e) =>
                                        contractForm.setData(
                                            'job_title',
                                            e.target.value,
                                        )
                                    }
                                />
                            </div>
                            <div className="grid gap-2">
                                <Label>Début</Label>
                                <Input
                                    type="date"
                                    value={contractForm.data.start_date}
                                    onChange={(e) =>
                                        contractForm.setData(
                                            'start_date',
                                            e.target.value,
                                        )
                                    }
                                />
                                <InputError
                                    message={contractForm.errors.start_date}
                                />
                            </div>
                            <div className="grid gap-2">
                                <Label>
                                    Fin{' '}
                                    <span className="text-muted-foreground font-normal">
                                        (optionnel)
                                    </span>
                                </Label>
                                <Input
                                    type="date"
                                    value={contractForm.data.end_date}
                                    onChange={(e) =>
                                        contractForm.setData(
                                            'end_date',
                                            e.target.value,
                                        )
                                    }
                                />
                                <InputError
                                    message={contractForm.errors.end_date}
                                />
                            </div>
                        </div>

                        <div className="grid gap-2">
                            <Label>Notes</Label>
                            <Textarea
                                value={contractForm.data.notes}
                                onChange={(e) =>
                                    contractForm.setData(
                                        'notes',
                                        e.target.value,
                                    )
                                }
                            />
                        </div>

                        <div className="grid gap-2">
                            <Label>Document signé</Label>
                            <Input
                                type="file"
                                accept=".pdf,.jpg,.jpeg,.png"
                                onChange={(e) =>
                                    contractForm.setData(
                                        'document',
                                        e.target.files?.[0] ?? null,
                                    )
                                }
                            />
                            <InputError
                                message={contractForm.errors.document}
                            />
                        </div>

                        <label className="flex items-center gap-2">
                            <Checkbox
                                checked={contractForm.data.is_current}
                                onCheckedChange={(checked) =>
                                    contractForm.setData(
                                        'is_current',
                                        checked === true,
                                    )
                                }
                            />
                            <span className="text-sm">Contrat courant</span>
                        </label>

                        <DialogFooter>
                            <Button
                                type="button"
                                variant="ghost"
                                onClick={closeContractModal}
                            >
                                Annuler
                            </Button>
                            <Button
                                type="submit"
                                disabled={contractForm.processing}
                            >
                                {editingContractId
                                    ? 'Enregistrer'
                                    : 'Créer le contrat'}
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

            <section className="border-border space-y-6 border-t pt-10">
                <div className="space-y-1.5">
                    <p className="text-muted-foreground text-xs font-medium tracking-[0.14em] uppercase">
                        Dossier
                    </p>
                    <h2 className="text-lg font-semibold tracking-tight">
                        Historique des contrats
                    </h2>
                    <p className="text-muted-foreground max-w-xl text-sm leading-relaxed">
                        Chronologie et avenants rattachés à chaque contrat.
                    </p>
                </div>

                {contracts.length === 0 ? (
                    <p className="text-muted-foreground text-sm">
                        Aucun contrat.
                    </p>
                ) : (
                    <ul className="divide-border divide-y border-y">
                        {contracts.map((contract) => {
                            const isExpanded = expandedId === contract.id;

                            return (
                                <li key={contract.id} className="py-4">
                                    <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
                                        <button
                                            type="button"
                                            className="min-w-0 flex-1 text-left"
                                            onClick={() =>
                                                setExpandedId(
                                                    isExpanded
                                                        ? null
                                                        : contract.id,
                                                )
                                            }
                                        >
                                            <div className="flex flex-wrap items-center gap-2">
                                                <p className="text-sm font-medium tracking-tight">
                                                    {contract.type_label}
                                                </p>
                                                {contract.is_current && (
                                                    <Badge
                                                        variant="secondary"
                                                        className="font-normal"
                                                    >
                                                        Courant
                                                    </Badge>
                                                )}
                                            </div>
                                            <p className="text-muted-foreground mt-1 text-xs">
                                                {formatDate(
                                                    contract.start_date,
                                                )}
                                                {' → '}
                                                {contract.end_date
                                                    ? formatDate(
                                                          contract.end_date,
                                                      )
                                                    : 'En cours'}
                                                {contract.job_title
                                                    ? ` · ${contract.job_title}`
                                                    : ''}
                                                {contract.amendments.length > 0
                                                    ? ` · ${contract.amendments.length} avenant${contract.amendments.length > 1 ? 's' : ''}`
                                                    : ''}
                                            </p>
                                        </button>

                                        <div className="flex shrink-0 flex-wrap gap-1">
                                            {contract.has_document && (
                                                <Button
                                                    variant="ghost"
                                                    size="icon"
                                                    asChild
                                                >
                                                    <a
                                                        href={EmployeeController.downloadContract.url(
                                                            {
                                                                employee:
                                                                    employeeId,
                                                                contract:
                                                                    contract.id,
                                                            },
                                                        )}
                                                    >
                                                        <Download />
                                                    </a>
                                                </Button>
                                            )}
                                            {canUpdate && (
                                                <>
                                                    <Button
                                                        type="button"
                                                        variant="ghost"
                                                        size="sm"
                                                        onClick={() =>
                                                            openEditContract(
                                                                contract,
                                                            )
                                                        }
                                                    >
                                                        Modifier
                                                    </Button>
                                                    <Button
                                                        type="button"
                                                        variant="ghost"
                                                        size="sm"
                                                        onClick={() => {
                                                            setExpandedId(
                                                                contract.id,
                                                            );
                                                            setAmendmentContractId(
                                                                contract.id,
                                                            );
                                                            amendmentForm.reset();
                                                            amendmentForm.clearErrors();
                                                        }}
                                                    >
                                                        <Plus />
                                                        Avenant
                                                    </Button>
                                                </>
                                            )}
                                        </div>
                                    </div>

                                    {isExpanded && (
                                        <div className="mt-4">
                                            {amendmentContractId ===
                                                contract.id &&
                                                canUpdate && (
                                                    <form
                                                        onSubmit={
                                                            submitAmendment
                                                        }
                                                        className="border-border mb-4 grid gap-3 border p-4 md:grid-cols-2"
                                                    >
                                                        <div className="grid gap-2">
                                                            <Label>
                                                                Date d’effet
                                                            </Label>
                                                            <Input
                                                                type="date"
                                                                value={
                                                                    amendmentForm
                                                                        .data
                                                                        .effective_date
                                                                }
                                                                onChange={(
                                                                    e,
                                                                ) =>
                                                                    amendmentForm.setData(
                                                                        'effective_date',
                                                                        e
                                                                            .target
                                                                            .value,
                                                                    )
                                                                }
                                                            />
                                                            <InputError
                                                                message={
                                                                    amendmentForm
                                                                        .errors
                                                                        .effective_date
                                                                }
                                                            />
                                                        </div>
                                                        <div className="grid gap-2">
                                                            <Label>Titre</Label>
                                                            <Input
                                                                value={
                                                                    amendmentForm
                                                                        .data
                                                                        .title
                                                                }
                                                                onChange={(
                                                                    e,
                                                                ) =>
                                                                    amendmentForm.setData(
                                                                        'title',
                                                                        e
                                                                            .target
                                                                            .value,
                                                                    )
                                                                }
                                                                placeholder="Ex. Augmentation"
                                                            />
                                                            <InputError
                                                                message={
                                                                    amendmentForm
                                                                        .errors
                                                                        .title
                                                                }
                                                            />
                                                        </div>
                                                        <div className="grid gap-2 md:col-span-2">
                                                            <Label>
                                                                Description
                                                            </Label>
                                                            <Textarea
                                                                value={
                                                                    amendmentForm
                                                                        .data
                                                                        .description
                                                                }
                                                                onChange={(
                                                                    e,
                                                                ) =>
                                                                    amendmentForm.setData(
                                                                        'description',
                                                                        e
                                                                            .target
                                                                            .value,
                                                                    )
                                                                }
                                                            />
                                                        </div>
                                                        <div className="grid gap-2">
                                                            <Label>
                                                                Document
                                                            </Label>
                                                            <Input
                                                                type="file"
                                                                accept=".pdf,.jpg,.jpeg,.png"
                                                                onChange={(
                                                                    e,
                                                                ) =>
                                                                    amendmentForm.setData(
                                                                        'document',
                                                                        e
                                                                            .target
                                                                            .files?.[0] ??
                                                                            null,
                                                                    )
                                                                }
                                                            />
                                                        </div>
                                                        <div className="flex items-end gap-2">
                                                            <Button
                                                                type="submit"
                                                                disabled={
                                                                    amendmentForm.processing
                                                                }
                                                            >
                                                                Ajouter
                                                            </Button>
                                                            <Button
                                                                type="button"
                                                                variant="ghost"
                                                                onClick={() =>
                                                                    setAmendmentContractId(
                                                                        null,
                                                                    )
                                                                }
                                                            >
                                                                Fermer
                                                            </Button>
                                                        </div>
                                                    </form>
                                                )}

                                            {contract.amendments.length ===
                                            0 ? (
                                                <p className="text-muted-foreground text-sm">
                                                    Aucun avenant sur ce
                                                    contrat.
                                                </p>
                                            ) : (
                                                <ul className="space-y-3">
                                                    {contract.amendments.map(
                                                        (amendment) => (
                                                            <li
                                                                key={
                                                                    amendment.id
                                                                }
                                                                className="flex items-start justify-between gap-3"
                                                            >
                                                                <div className="min-w-0">
                                                                    <p className="text-sm font-medium tracking-tight">
                                                                        {
                                                                            amendment.title
                                                                        }
                                                                    </p>
                                                                    <p className="text-muted-foreground text-xs">
                                                                        Effet
                                                                        le{' '}
                                                                        {formatDate(
                                                                            amendment.effective_date,
                                                                        )}
                                                                        {amendment
                                                                            .created_by
                                                                            ?.name
                                                                            ? ` · ${amendment.created_by.name}`
                                                                            : ''}
                                                                    </p>
                                                                    {amendment.description && (
                                                                        <p className="text-muted-foreground mt-1 text-xs leading-relaxed">
                                                                            {
                                                                                amendment.description
                                                                            }
                                                                        </p>
                                                                    )}
                                                                </div>
                                                                <div className="flex shrink-0 gap-1">
                                                                    {amendment.has_document && (
                                                                        <Button
                                                                            variant="ghost"
                                                                            size="icon"
                                                                            asChild
                                                                        >
                                                                            <a
                                                                                href={EmployeeController.downloadAmendment.url(
                                                                                    {
                                                                                        employee:
                                                                                            employeeId,
                                                                                        contract:
                                                                                            contract.id,
                                                                                        amendment:
                                                                                            amendment.id,
                                                                                    },
                                                                                )}
                                                                            >
                                                                                <Download />
                                                                            </a>
                                                                        </Button>
                                                                    )}
                                                                    {canUpdate && (
                                                                        <ConfirmDialog
                                                                            trigger={
                                                                                <Button
                                                                                    variant="ghost"
                                                                                    size="icon"
                                                                                >
                                                                                    <Trash2 />
                                                                                </Button>
                                                                            }
                                                                            title="Supprimer cet avenant ?"
                                                                            confirmLabel="Supprimer"
                                                                            onConfirm={() =>
                                                                                router.delete(
                                                                                    EmployeeController.destroyAmendment.url(
                                                                                        {
                                                                                            employee:
                                                                                                employeeId,
                                                                                            contract:
                                                                                                contract.id,
                                                                                            amendment:
                                                                                                amendment.id,
                                                                                        },
                                                                                    ),
                                                                                    {
                                                                                        preserveScroll: true,
                                                                                    },
                                                                                )
                                                                            }
                                                                        />
                                                                    )}
                                                                </div>
                                                            </li>
                                                        ),
                                                    )}
                                                </ul>
                                            )}
                                        </div>
                                    )}
                                </li>
                            );
                        })}
                    </ul>
                )}
            </section>
        </div>
    );
}
