import {
    Clock,
    CheckCircle,
    AlertCircle,
    Trash2,
    FileText,
} from 'lucide-react';

export type Contract = {
    id: string | number;
    docName: string;
    docNumber: string;
    counterParty: string;
    internalParty: string;
    isSigned: boolean | number | string;
    value: number;
    created_at: string;
    end_date?: string;
    duration?: string;
    contract_file?: string;
};

type ContractsTableProps = {
    contracts: Contract[];
    onDelete?: (id: string | number) => void;
};

function formatCurrency(value: number): string {
    return new Intl.NumberFormat('id-ID', {
        style: 'currency',
        currency: 'IDR',
        minimumFractionDigits: 0,
    }).format(value);
}

function formatDate(date: Date | string): string {
    if (!date) return '-';
    const dateObj = typeof date === 'string' ? new Date(date) : date;
    return new Intl.DateTimeFormat('id-ID', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
    }).format(dateObj);
}

function getStatusColor(isSigned: boolean | number | string) {
    const signed =
        isSigned === true ||
        isSigned === 1 ||
        isSigned === '1' ||
        isSigned === 'true';
    if (signed) {
        return {
            bg: 'bg-green-950/70 border border-green-800',
            text: 'text-green-400',
            icon: CheckCircle,
            label: 'Active',
        };
    }
    return {
        bg: 'bg-yellow-950/70 border border-yellow-800',
        text: 'text-yellow-400',
        icon: Clock,
        label: 'Pending',
    };
}

export function ContractsTable({ contracts, onDelete }: ContractsTableProps) {
    if (contracts.length === 0) {
        return (
            <div className="rounded-lg border border-slate-700 bg-slate-800 p-8 text-center">
                <AlertCircle className="mx-auto mb-3 h-12 w-12 text-slate-400" />
                <p className="text-slate-400">
                    Tidak ada kontrak. Mulai upload kontrak baru!
                </p>
            </div>
        );
    }

    return (
        <div className="overflow-hidden rounded-lg border border-slate-700 bg-slate-800 shadow-sm">
            {/* Filter Status Ringkas */}
            <div className="flex flex-wrap items-center gap-4 border-b border-slate-700 bg-slate-800/50 px-6 py-4">
                <div className="flex items-center gap-2">
                    <span className="text-sm font-medium text-slate-200">
                        All
                    </span>
                    <span className="inline-flex items-center rounded-full bg-slate-700 px-2 py-0.5 text-xs font-semibold text-slate-300">
                        {contracts.length}
                    </span>
                </div>
                <div className="flex items-center gap-2 border-l border-slate-700 pl-4">
                    <span className="text-sm font-medium text-slate-400">
                        Active
                    </span>
                    <span className="text-sm font-semibold text-green-400">
                        {
                            contracts.filter(
                                (c) =>
                                    c.isSigned === true ||
                                    c.isSigned === 1 ||
                                    c.isSigned === '1' ||
                                    c.isSigned === 'true',
                            ).length
                        }
                    </span>
                </div>
                <div className="flex items-center gap-2 border-l border-slate-700 pl-4">
                    <span className="text-sm font-medium text-slate-400">
                        Pending
                    </span>
                    <span className="text-sm font-semibold text-yellow-400">
                        {
                            contracts.filter(
                                (c) =>
                                    !(
                                        c.isSigned === true ||
                                        c.isSigned === 1 ||
                                        c.isSigned === '1' ||
                                        c.isSigned === 'true'
                                    ),
                            ).length
                        }
                    </span>
                </div>
            </div>

            {/* Kontainer Tabel Utama */}
            <div className="overflow-x-auto">
                <table className="w-full border-collapse text-left">
                    <thead className="border-b border-slate-700 bg-slate-700/30">
                        <tr>
                            <th className="px-6 py-3 text-xs font-semibold tracking-wider text-slate-300 uppercase">
                                Contract
                            </th>
                            <th className="px-6 py-3 text-xs font-semibold tracking-wider text-slate-300 uppercase">
                                Counterparty
                            </th>
                            <th className="px-6 py-3 text-xs font-semibold tracking-wider text-slate-300 uppercase">
                                Status
                            </th>
                            <th className="px-6 py-3 text-xs font-semibold tracking-wider text-slate-300 uppercase">
                                Owner
                            </th>
                            <th className="px-6 py-3 text-right text-xs font-semibold tracking-wider text-slate-300 uppercase">
                                Value
                            </th>
                            <th className="px-6 py-3 text-xs font-semibold tracking-wider text-slate-300 uppercase">
                                End Date
                            </th>
                            {/* Tambah Header Kolom PDF */}
                            <th className="px-6 py-3 text-center text-xs font-semibold tracking-wider text-slate-300 uppercase">
                                Attachment
                            </th>
                            <th className="px-6 py-3 text-center text-xs font-semibold tracking-wider text-slate-300 uppercase">
                                Actions
                            </th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-700/50">
                        {contracts.map((contract, idx) => {
                            const status = getStatusColor(contract.isSigned);
                            const StatusIcon = status.icon;

                            return (
                                <tr
                                    key={contract.id}
                                    className={`transition-colors hover:bg-slate-700/30 ${
                                        idx % 2 === 0
                                            ? 'bg-slate-800'
                                            : 'bg-slate-900/40'
                                    }`}
                                >
                                    <td className="px-6 py-4">
                                        <div>
                                            <p className="font-medium text-white">
                                                {contract.docName}
                                            </p>
                                            <p className="text-xs text-slate-400">
                                                {contract.docNumber}
                                            </p>
                                        </div>
                                    </td>
                                    <td className="px-6 py-4 text-sm text-slate-300">
                                        {contract.counterParty}
                                    </td>
                                    <td className="px-6 py-4">
                                        <span
                                            className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium ${status.bg} ${status.text}`}
                                        >
                                            <StatusIcon className="h-3 w-3" />
                                            {status.label}
                                        </span>
                                    </td>
                                    <td className="px-6 py-4 text-sm text-slate-300">
                                        {contract.internalParty || '-'}
                                    </td>
                                    <td className="px-6 py-4 text-right font-medium text-white">
                                        {formatCurrency(contract.value)}
                                    </td>
                                    <td className="px-6 py-4 text-sm text-slate-300">
                                        <div className="flex flex-col">
                                            {contract.end_date &&
                                            new Date(contract.end_date) <
                                                new Date() ? (
                                                <span className="font-medium text-red-400">
                                                    Expired
                                                </span>
                                            ) : (
                                                <>
                                                    <span>
                                                        Mulai:{' '}
                                                        {formatDate(
                                                            contract.created_at,
                                                        )}
                                                    </span>
                                                    <span className="mt-0.5 text-xs text-slate-500">
                                                        Akhir:{' '}
                                                        {contract.end_date
                                                            ? formatDate(
                                                                  contract.end_date,
                                                              )
                                                            : '-'}
                                                    </span>
                                                </>
                                            )}
                                        </div>
                                    </td>

                                    {/* Tombol Berkas PDF */}
                                    <td className="px-6 py-4 text-center">
                                        {contract.contract_file ? (
                                            <a
                                                href={`/storage/${contract.contract_file}`}
                                                target="_blank"
                                                rel="noreferrer"
                                                className="inline-flex items-center gap-1.5 rounded-md border border-red-500/20 bg-red-500/10 px-2.5 py-1 text-xs font-medium text-red-400 transition-colors hover:bg-red-600 hover:text-white"
                                                title="Lihat PDF"
                                            >
                                                <FileText className="h-3.5 w-3.5" />
                                                <span>PDF</span>
                                            </a>
                                        ) : (
                                            <span className="text-xs text-slate-600">
                                                —
                                            </span>
                                        )}
                                    </td>

                                    <td className="px-6 py-4 text-center">
                                        {onDelete && (
                                            <button
                                                onClick={() =>
                                                    onDelete(contract.id)
                                                }
                                                className="inline-flex items-center justify-center rounded-lg p-2 text-slate-400 transition-colors hover:bg-red-950/50 hover:text-red-400"
                                            >
                                                <Trash2 className="h-4 w-4" />
                                            </button>
                                        )}
                                    </td>
                                </tr>
                            );
                        })}
                    </tbody>
                </table>
            </div>
        </div>
    );
}
