import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { router } from '@inertiajs/react';
import { Copy, MoreVertical, Pencil, RotateCcw, Trash2 } from 'lucide-react';
import * as React from 'react';
import { SourceBadge } from './source-badge';
import type { LedgerRow, LedgerSource } from './types';

interface Props {
    row: LedgerRow;
    selected?: boolean;
    onToggleSelect?: (checked: boolean) => void;
    onOpenSource?: (source: LedgerSource, sourceId: number) => void;
    onEditSource?: (source: LedgerSource, sourceId: number) => void;
    onDeleteSource?: (source: LedgerSource, sourceId: number) => void;
}

function frDate(iso: string): string {
    const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
    return m ? `${m[3]}/${m[2]}/${m[1]}` : iso;
}
function timeOf(createdAt: string | null): string | null {
    if (!createdAt) return null;
    const d = new Date(createdAt);
    if (isNaN(d.getTime())) return null;
    return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
}
function fmt(n: number): string {
    return n.toLocaleString('fr-TN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

/**
 * The action a row is waiting on — drives the notification badge + the
 * coloured left border so a mobile user spots their to-dos at a glance.
 */
function resolveAction(row: LedgerRow): { label: string; chip: string; border: string } | null {
    if (row.alloc_can_report)  return { label: '▶ À traiter',          chip: 'bg-emerald-100 text-emerald-700', border: 'border-l-emerald-500' };
    if (row.alloc_can_approve) return { label: '✔ À approuver',        chip: 'bg-amber-100 text-amber-700',     border: 'border-l-amber-500' };
    if (row.alloc_can_return)  return { label: '↩ Retour à confirmer', chip: 'bg-sky-100 text-sky-700',         border: 'border-l-sky-500' };
    if (row.facture_pending)   return { label: '⏳ Facture en attente', chip: 'bg-amber-100 text-amber-700',     border: 'border-l-amber-500' };
    return null;
}

export function MobileLedgerCard({ row, selected = false, onToggleSelect, onOpenSource, onEditSource, onDeleteSource }: Props) {
    const isDeleted = row.deleted_at !== null;
    const isMirror = row.source !== 'manual';
    const isEntree = row.type === 'entree';
    const action = isDeleted ? null : resolveAction(row);
    const time = timeOf(row.created_at);

    // Source id: allocation rows use their own id; classic mirrors use the linked id.
    const sourceId = row.source === 'allocation'
        ? row.id
        : (row.recovery_id ?? row.expense_id ?? row.receipt_id);

    const openSource = () => {
        if (isMirror && sourceId != null && onOpenSource) onOpenSource(row.source, sourceId);
    };
    const onDelete = () => {
        if (!confirm('Supprimer cette ligne ?')) return;
        router.delete(route('fond-de-caisse.destroy', { id: row.id }), { preserveScroll: true, only: ['rows', 'summary', 'flash'] });
    };
    const onRestore = () => {
        router.post(route('fond-de-caisse.restore', { id: row.id }), {}, { preserveScroll: true, only: ['rows', 'summary', 'flash'] });
    };
    const onDuplicate = () => {
        router.post(route('fond-de-caisse.duplicate', { id: row.id }), {}, { preserveScroll: true, only: ['rows', 'summary', 'flash'] });
    };

    const soldeClass = (row.solde ?? 0) >= 0 ? 'text-emerald-700' : 'text-red-700';

    return (
        <div
            className={`bg-background rounded-lg border border-l-4 p-3 ${
                action ? action.border : 'border-l-transparent'
            } ${isDeleted ? 'opacity-60' : ''}`}
        >
            {/* Top row: badge + date + menu */}
            <div className="flex items-start justify-between gap-2">
                <div className="flex items-center gap-2">
                    {!isMirror && !isDeleted && onToggleSelect && (
                        <Checkbox
                            checked={selected}
                            onCheckedChange={(v) => onToggleSelect(v === true)}
                            aria-label="Sélectionner"
                        />
                    )}
                    <SourceBadge row={row} onClick={isMirror ? openSource : undefined} />
                </div>
                <div className="flex items-center gap-1">
                    <span className="text-muted-foreground text-xs tabular-nums">
                        {frDate(row.date)}{time ? ` · ${time}` : ''}
                    </span>
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button variant="ghost" size="icon" className="h-7 w-7">
                                <MoreVertical className="h-4 w-4" />
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                            {isDeleted ? (
                                <DropdownMenuItem onClick={onRestore} className="text-emerald-700 focus:text-emerald-700">
                                    <RotateCcw className="mr-2 h-4 w-4" /> Restaurer
                                </DropdownMenuItem>
                            ) : isMirror ? (
                                <>
                                    <DropdownMenuItem onClick={openSource}>
                                        <Pencil className="mr-2 h-4 w-4" />
                                        {row.alloc_can_report ? 'Traiter' : row.alloc_can_approve ? 'Approuver' : row.alloc_can_return ? 'Confirmer le retour' : 'Voir le détail'}
                                    </DropdownMenuItem>
                                    {(row.source === 'recovery' || row.source === 'expense') && onEditSource && sourceId != null && (
                                        <DropdownMenuItem onClick={() => onEditSource(row.source, sourceId)}>
                                            <Pencil className="mr-2 h-4 w-4" /> Modifier
                                        </DropdownMenuItem>
                                    )}
                                    {(row.source === 'recovery' || row.source === 'expense') && onDeleteSource && sourceId != null && (
                                        <DropdownMenuItem onClick={() => onDeleteSource(row.source, sourceId)} className="text-red-600 focus:text-red-600">
                                            <Trash2 className="mr-2 h-4 w-4" /> Supprimer
                                        </DropdownMenuItem>
                                    )}
                                </>
                            ) : (
                                <>
                                    <DropdownMenuItem onClick={onDuplicate}>
                                        <Copy className="mr-2 h-4 w-4" /> Dupliquer
                                    </DropdownMenuItem>
                                    <DropdownMenuItem onClick={onDelete} className="text-red-600 focus:text-red-600">
                                        <Trash2 className="mr-2 h-4 w-4" /> Supprimer
                                    </DropdownMenuItem>
                                </>
                            )}
                        </DropdownMenuContent>
                    </DropdownMenu>
                </div>
            </div>

            {/* Designation — tap opens the detail/action dialog for mirror rows */}
            <button
                type="button"
                onClick={openSource}
                disabled={!isMirror}
                className="mt-1.5 block w-full text-left"
            >
                <div className="text-sm font-medium leading-snug">{row.designation}</div>
                {row.owner_name && (
                    <div className="text-muted-foreground mt-0.5 text-[11px]">👤 {row.owner_name}</div>
                )}
            </button>

            {/* Amounts + solde */}
            <div className="mt-2 flex items-end justify-between border-t pt-2">
                <div className={`text-base font-semibold tabular-nums ${isEntree ? 'text-emerald-700' : 'text-red-700'}`}>
                    {isEntree ? '+' : '−'}{fmt(row.amount)} TND
                </div>
                <div className="text-right">
                    <div className="text-muted-foreground text-[10px] uppercase tracking-wide">Solde</div>
                    <div className={`text-sm font-semibold tabular-nums ${soldeClass}`}>
                        {row.solde !== null ? `${fmt(row.solde)} TND` : '—'}
                    </div>
                </div>
            </div>

            {/* Notification badge — the to-do */}
            {action && (
                <button
                    type="button"
                    onClick={openSource}
                    className={`mt-2 w-full rounded-md px-2 py-1.5 text-xs font-medium ${action.chip}`}
                >
                    {action.label} — appuyer pour ouvrir
                </button>
            )}
        </div>
    );
}
