import { Head, Link, router } from '@inertiajs/react';
import { ArrowLeft, Pencil, RotateCcw, Send, Trash2, XCircle } from 'lucide-react';
import { useState } from 'react';
import JournalEntryController from '@/actions/App/Http/Controllers/Admin/JournalEntryController';
import { ConfirmDialog } from '@/components/confirm-dialog';
import Heading from '@/components/heading';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
    Table,
    TableBody,
    TableCell,
    TableFooter,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { formatCurrency, formatDate } from '@/lib/utils';
import { dashboard } from '@/routes';
import { edit, index } from '@/routes/admin/journal-entries';
import { JournalEntryStatusBadge } from './status-badge';

type Line = {
    id: number;
    chart_of_account_id: number;
    cost_center_id: number | null;
    account: { id: number; code: string; label: string } | null;
    cost_center: { id: number; code: string; name: string } | null;
    label: string | null;
    debit: string | number;
    credit: string | number;
};

type Entry = {
    id: number;
    reference: string;
    journal_type: string;
    journal_type_label: string;
    entry_date: string | null;
    label: string;
    status: string;
    status_label: string;
    total_debit: string | number;
    total_credit: string | number;
    source_type: string | null;
    source_id: number | null;
    creator: { id: number; name: string } | null;
    submitter: { id: number; name: string } | null;
    submitted_at: string | null;
    manager_validator: { id: number; name: string } | null;
    manager_validated_at: string | null;
    rejector: { id: number; name: string } | null;
    rejected_at: string | null;
    rejection_reason: string | null;
    poster: { id: number; name: string } | null;
    posted_at: string | null;
    reversal_of: { id: number; reference: string } | null;
    reversed_by: { id: number; reference: string } | null;
    created_at: string | null;
    lines: Line[];
};

export default function JournalEntriesShow({
    entry,
    can,
}: {
    entry: Entry;
    can: {
        update: boolean;
        delete: boolean;
        submit: boolean;
        managerApprove: boolean;
        reject: boolean;
        post: boolean;
        reverse: boolean;
    };
}) {
    const [rejectOpen, setRejectOpen] = useState(false);
    const [rejectionReason, setRejectionReason] = useState('');

    return (
        <>
            <Head title={entry.reference} />

            <div className="flex h-full flex-1 flex-col gap-6 p-4 md:p-6">
                <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <Heading
                        title={entry.reference}
                        description={entry.label}
                    />
                    <div className="flex flex-wrap gap-2">
                        <Button variant="outline" asChild>
                            <Link href={index()}>
                                <ArrowLeft />
                                Retour
                            </Link>
                        </Button>
                        {can.update && (
                            <Button variant="outline" asChild>
                                <Link href={edit(entry.id)}>
                                    <Pencil />
                                    Modifier
                                </Link>
                            </Button>
                        )}
                        {can.submit && (
                            <ConfirmDialog
                                trigger={
                                    <Button variant="default">
                                        <Send />
                                        Soumettre
                                    </Button>
                                }
                                title={`Soumettre l'écriture ${entry.reference} ?`}
                                description="L'écriture sera transmise au manager pour validation avant comptabilisation."
                                confirmLabel="Soumettre"
                                variant="default"
                                onConfirm={() =>
                                    router.post(
                                        JournalEntryController.submit.url(
                                            entry.id,
                                        ),
                                        {},
                                        { preserveScroll: true },
                                    )
                                }
                            />
                        )}
                        {can.managerApprove && (
                            <ConfirmDialog
                                trigger={
                                    <Button variant="default">
                                        Valider (manager)
                                    </Button>
                                }
                                title={`Valider l'écriture ${entry.reference} ?`}
                                description="En tant que manager, vous autorisez la comptabilisation de cette écriture."
                                confirmLabel="Valider"
                                variant="default"
                                onConfirm={() =>
                                    router.post(
                                        JournalEntryController.managerApprove.url(
                                            entry.id,
                                        ),
                                        {},
                                        { preserveScroll: true },
                                    )
                                }
                            />
                        )}
                        {can.reject && (
                            <Button
                                variant="outline"
                                onClick={() => setRejectOpen(true)}
                            >
                                <XCircle />
                                Rejeter
                            </Button>
                        )}
                        {can.post && (
                            <ConfirmDialog
                                trigger={
                                    <Button variant="default">
                                        Comptabiliser
                                    </Button>
                                }
                                title={`Comptabiliser l'écriture ${entry.reference} ?`}
                                description="L'écriture validée par le manager sera comptabilisée et deviendra immuable."
                                confirmLabel="Comptabiliser"
                                variant="default"
                                onConfirm={() =>
                                    router.post(
                                        JournalEntryController.post.url(
                                            entry.id,
                                        ),
                                        {},
                                        { preserveScroll: true },
                                    )
                                }
                            />
                        )}
                        {can.reverse && (
                            <ConfirmDialog
                                trigger={
                                    <Button variant="outline">
                                        <RotateCcw />
                                        Extourner
                                    </Button>
                                }
                                title={`Extourner l'écriture ${entry.reference} ?`}
                                description="Une contre-écriture (débit/crédit inversés) sera créée et comptabilisée immédiatement."
                                confirmLabel="Extourner"
                                onConfirm={() =>
                                    router.post(
                                        JournalEntryController.reverse.url(
                                            entry.id,
                                        ),
                                        {},
                                        { preserveScroll: true },
                                    )
                                }
                            />
                        )}
                        {can.delete && (
                            <ConfirmDialog
                                trigger={
                                    <Button variant="destructive">
                                        <Trash2 />
                                        Supprimer
                                    </Button>
                                }
                                title={`Supprimer l'écriture ${entry.reference} ?`}
                                description="Cette action est irréversible."
                                confirmLabel="Supprimer"
                                onConfirm={() =>
                                    router.delete(
                                        JournalEntryController.destroy.url(
                                            entry.id,
                                        ),
                                    )
                                }
                            />
                        )}
                    </div>
                </div>

                <div className="grid gap-6 lg:grid-cols-3">
                    <Card className="lg:col-span-2">
                        <CardHeader>
                            <CardTitle>Lignes</CardTitle>
                            <CardDescription>
                                {entry.journal_type_label} ·{' '}
                                {formatDate(entry.entry_date)}
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Compte</TableHead>
                                        <TableHead>Analytique</TableHead>
                                        <TableHead>Libellé</TableHead>
                                        <TableHead className="text-right">
                                            Débit
                                        </TableHead>
                                        <TableHead className="text-right">
                                            Crédit
                                        </TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {entry.lines.map((line) => (
                                        <TableRow key={line.id}>
                                            <TableCell className="font-mono text-sm">
                                                {line.account
                                                    ? `${line.account.code} — ${line.account.label}`
                                                    : '—'}
                                            </TableCell>
                                            <TableCell className="text-sm text-muted-foreground">
                                                {line.cost_center
                                                    ? `${line.cost_center.code} — ${line.cost_center.name}`
                                                    : '—'}
                                            </TableCell>
                                            <TableCell className="text-muted-foreground">
                                                {line.label ?? '—'}
                                            </TableCell>
                                            <TableCell className="text-right tabular-nums">
                                                {Number(line.debit) > 0
                                                    ? formatCurrency(line.debit)
                                                    : ''}
                                            </TableCell>
                                            <TableCell className="text-right tabular-nums">
                                                {Number(line.credit) > 0
                                                    ? formatCurrency(
                                                          line.credit,
                                                      )
                                                    : ''}
                                            </TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                                <TableFooter>
                                    <TableRow>
                                        <TableCell colSpan={2}>
                                            Total
                                        </TableCell>
                                        <TableCell className="text-right font-semibold tabular-nums">
                                            {formatCurrency(entry.total_debit)}
                                        </TableCell>
                                        <TableCell className="text-right font-semibold tabular-nums">
                                            {formatCurrency(
                                                entry.total_credit,
                                            )}
                                        </TableCell>
                                    </TableRow>
                                </TableFooter>
                            </Table>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardHeader>
                            <CardTitle>Détails</CardTitle>
                        </CardHeader>
                        <CardContent className="space-y-4 text-sm">
                            <div className="flex items-center justify-between">
                                <span className="text-muted-foreground">
                                    Statut
                                </span>
                                <JournalEntryStatusBadge
                                    status={entry.status}
                                    label={entry.status_label}
                                />
                            </div>
                            <div className="flex items-center justify-between">
                                <span className="text-muted-foreground">
                                    Journal
                                </span>
                                <span className="font-medium">
                                    {entry.journal_type_label}
                                </span>
                            </div>
                            <div className="flex items-center justify-between">
                                <span className="text-muted-foreground">
                                    Origine
                                </span>
                                <span className="font-medium">
                                    {entry.source_type
                                        ? `${entry.source_type} #${entry.source_id}`
                                        : 'Saisie manuelle'}
                                </span>
                            </div>
                            <div className="flex items-center justify-between">
                                <span className="text-muted-foreground">
                                    Créée par
                                </span>
                                <span className="font-medium">
                                    {entry.creator?.name ?? '—'}
                                </span>
                            </div>
                            <div className="flex items-center justify-between">
                                <span className="text-muted-foreground">
                                    Créée le
                                </span>
                                <span className="font-medium">
                                    {formatDate(entry.created_at)}
                                </span>
                            </div>
                            {entry.submitter && (
                                <div className="flex items-center justify-between">
                                    <span className="text-muted-foreground">
                                        Soumise par
                                    </span>
                                    <span className="font-medium">
                                        {entry.submitter.name}
                                    </span>
                                </div>
                            )}
                            {entry.submitted_at && (
                                <div className="flex items-center justify-between">
                                    <span className="text-muted-foreground">
                                        Soumise le
                                    </span>
                                    <span className="font-medium">
                                        {formatDate(entry.submitted_at)}
                                    </span>
                                </div>
                            )}
                            {entry.manager_validator && (
                                <div className="flex items-center justify-between">
                                    <span className="text-muted-foreground">
                                        Validée par (manager)
                                    </span>
                                    <span className="font-medium">
                                        {entry.manager_validator.name}
                                    </span>
                                </div>
                            )}
                            {entry.manager_validated_at && (
                                <div className="flex items-center justify-between">
                                    <span className="text-muted-foreground">
                                        Validée le
                                    </span>
                                    <span className="font-medium">
                                        {formatDate(entry.manager_validated_at)}
                                    </span>
                                </div>
                            )}
                            {entry.rejection_reason && (
                                <div className="rounded-md border border-orange-200 bg-orange-50 p-3 text-orange-900 dark:border-orange-900 dark:bg-orange-950/40 dark:text-orange-200">
                                    <p className="text-xs font-medium uppercase tracking-wide">
                                        Motif de rejet
                                    </p>
                                    <p className="mt-1">{entry.rejection_reason}</p>
                                </div>
                            )}
                            {entry.poster && (
                                <div className="flex items-center justify-between">
                                    <span className="text-muted-foreground">
                                        Comptabilisée par
                                    </span>
                                    <span className="font-medium">
                                        {entry.poster.name}
                                    </span>
                                </div>
                            )}
                            {entry.posted_at && (
                                <div className="flex items-center justify-between">
                                    <span className="text-muted-foreground">
                                        Comptabilisée le
                                    </span>
                                    <span className="font-medium">
                                        {formatDate(entry.posted_at)}
                                    </span>
                                </div>
                            )}
                            {entry.reversal_of && (
                                <div className="flex items-center justify-between">
                                    <span className="text-muted-foreground">
                                        Extourne de
                                    </span>
                                    <Link
                                        className="font-medium underline"
                                        href={
                                            JournalEntryController.show(
                                                entry.reversal_of.id,
                                            ).url
                                        }
                                    >
                                        {entry.reversal_of.reference}
                                    </Link>
                                </div>
                            )}
                            {entry.reversed_by && (
                                <div className="flex items-center justify-between">
                                    <span className="text-muted-foreground">
                                        Extournée par
                                    </span>
                                    <Link
                                        className="font-medium underline"
                                        href={
                                            JournalEntryController.show(
                                                entry.reversed_by.id,
                                            ).url
                                        }
                                    >
                                        {entry.reversed_by.reference}
                                    </Link>
                                </div>
                            )}
                        </CardContent>
                    </Card>
                </div>
            </div>

            <Dialog open={rejectOpen} onOpenChange={setRejectOpen}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Rejeter l'écriture {entry.reference}</DialogTitle>
                        <DialogDescription>
                            L'écriture retournera en brouillon modifiable. Vous
                            pouvez indiquer un motif de rejet.
                        </DialogDescription>
                    </DialogHeader>
                    <div className="grid gap-2">
                        <Label htmlFor="rejection_reason">Motif (optionnel)</Label>
                        <Textarea
                            id="rejection_reason"
                            value={rejectionReason}
                            onChange={(e) => setRejectionReason(e.target.value)}
                            rows={3}
                        />
                    </div>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setRejectOpen(false)}>
                            Annuler
                        </Button>
                        <Button
                            variant="destructive"
                            onClick={() =>
                                router.post(
                                    JournalEntryController.reject.url(entry.id),
                                    { rejection_reason: rejectionReason || null },
                                    {
                                        preserveScroll: true,
                                        onSuccess: () => {
                                            setRejectOpen(false);
                                            setRejectionReason('');
                                        },
                                    },
                                )
                            }
                        >
                            Rejeter
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </>
    );
}

JournalEntriesShow.layout = {
    breadcrumbs: [
        { title: 'Tableau de bord', href: dashboard() },
        { title: 'Écritures', href: index() },
        { title: 'Détail', href: '#' },
    ],
};

