import { useMemo } from 'react';
import { router } from '@inertiajs/react';
import AIChatPopup from '../components/chat-popup';
import {
    Calendar,
    AlertCircle,
    CheckCircle,
    Clock,
    Trash2,
} from 'lucide-react';

interface Contract {
    id: string | number;
    docName: string;
    docNumber: string;
    counterParty: string;
    contractDuration: string;
    createdAt?: string | Date;
    created_at?: string | Date;
    end_date?: string;
}

interface RenewalsTableProps {
    contracts: Contract[];
}

type RenewalStatus = 'active' | 'expiring-soon' | 'expired';

function getRenewalStatus(contract: Contract): RenewalStatus {
    if (!contract.end_date) return 'active';

    const today = new Date();
    const endDate = new Date(contract.end_date);

    const daysUntil = Math.ceil(
        (endDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24),
    );

    if (daysUntil < 0) return 'expired';
    if (daysUntil <= 30) return 'expiring-soon';
    return 'active';
}

function getDaysUntil(contract: Contract): number {
    if (!contract.end_date) return 999999; // Angka besar agar tidak dianggap segera kedaluwarsa

    const today = new Date();
    const endDate = new Date(contract.end_date);
    const diff = endDate.getTime() - today.getTime();
    return Math.ceil(diff / (1000 * 60 * 60 * 24));
}

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

function StatusBadge({ status }: { status: RenewalStatus }) {
    const styles = {
        active: 'bg-emerald-950 text-emerald-400 border border-emerald-800/60',
        'expiring-soon':
            'bg-orange-950 text-orange-400 border border-orange-800/60',
        expired: 'bg-red-950 text-red-400 border border-red-800/60',
    };

    const labels = {
        active: 'Active',
        'expiring-soon': 'Expiring Soon',
        expired: 'Expired',
    };

    return (
        <span
            className={`inline-block rounded-full border px-2.5 py-0.5 text-xs font-medium ${styles[status]}`}
        >
            {labels[status]}
        </span>
    );
}

export default function RenewalsTable({ contracts = [] }: RenewalsTableProps) {
    const handleDelete = (id: string | number) => {
        if (
            confirm('Yakin ingin menghapus kontrak ini dari daftar pembaruan?')
        ) {
            router.delete(`/contracts/${id}`, {
                preserveScroll: true,
            });
        }
    };

    const groupedContracts = useMemo(() => {
        return {
            active: contracts.filter((c) => getRenewalStatus(c) === 'active'),
            'expiring-soon': contracts.filter(
                (c) => getRenewalStatus(c) === 'expiring-soon',
            ),
            expired: contracts.filter((c) => getRenewalStatus(c) === 'expired'),
        };
    }, [contracts]);

    const renderContractList = (
        contractList: Contract[],
        status: RenewalStatus,
    ) => {
        if (contractList.length === 0) {
            return (
                <tr>
                    <td
                        colSpan={6}
                        className="bg-slate-950/20 px-6 py-8 text-center text-slate-500"
                    >
                        Tidak ada kontrak dalam kategori ini
                    </td>
                </tr>
            );
        }

        return contractList.map((contract) => {
            const daysUntil = getDaysUntil(contract);
            const endDate = contract.end_date
                ? formatDate(contract.end_date)
                : '-';

            return (
                <tr
                    key={contract.id}
                    className="border-b border-slate-800 bg-slate-950/40 transition-colors hover:bg-slate-900/40"
                >
                    <td className="px-6 py-4">
                        <div>
                            <p className="font-medium text-white">
                                {contract.docName}
                            </p>
                            <p className="mt-0.5 text-xs text-slate-500">
                                {contract.docNumber}
                            </p>
                        </div>
                    </td>
                    <td className="px-6 py-4">
                        <p className="text-slate-300">
                            {contract.counterParty}
                        </p>
                    </td>
                    <td className="px-6 py-4">
                        <StatusBadge status={status} />
                    </td>
                    <td className="px-6 py-4">
                        <div className="flex items-center gap-2 text-sm text-slate-300">
                            <Calendar className="h-4 w-4 text-slate-500" />
                            {endDate}
                        </div>
                    </td>
                    <td className="px-6 py-4">
                        <div className="flex items-center gap-2">
                            {daysUntil >= 0 ? (
                                <>
                                    <Clock className="h-4 w-4 text-blue-400" />
                                    <span className="text-sm font-medium text-slate-200">
                                        {daysUntil} hari
                                    </span>
                                </>
                            ) : (
                                <>
                                    <AlertCircle className="h-4 w-4 text-red-400" />
                                    <span className="text-sm font-medium text-red-400">
                                        Expired
                                    </span>
                                </>
                            )}
                        </div>
                    </td>
                    <td className="px-6 py-4 text-center">
                        <button
                            onClick={() => handleDelete(contract.id)}
                            className="inline-flex items-center rounded p-1.5 text-slate-500 transition-colors hover:bg-red-500/10 hover:text-red-400"
                            title="Hapus Kontrak"
                        >
                            <Trash2 className="h-4 w-4" />
                        </button>
                    </td>
                </tr>
            );
        });
    };

    return (
        <div className="space-y-8 pt-6">
            {/* 1. Kategori Active */}
            <section className="overflow-hidden rounded-lg border border-slate-800 bg-slate-900/20">
                <div className="flex items-center gap-3 border-b border-slate-800 bg-slate-900/60 px-6 py-4">
                    <CheckCircle className="h-5 w-5 text-emerald-400" />
                    <div>
                        <h3 className="text-base font-semibold text-white">
                            Active Contracts
                        </h3>
                        <p className="mt-0.5 text-xs text-slate-400">
                            {groupedContracts.active.length} dokumen aman
                        </p>
                    </div>
                </div>
                <div className="overflow-x-auto">
                    <table className="w-full border-collapse text-left text-sm">
                        <thead className="border-b border-slate-800 bg-slate-900/40 text-xs font-semibold tracking-wider text-slate-400 uppercase">
                            <tr>
                                <th className="px-6 py-3">Contract</th>
                                <th className="px-6 py-3">Counterparty</th>
                                <th className="px-6 py-3">Status</th>
                                <th className="px-6 py-3">End Date</th>
                                <th className="px-6 py-3">Days Left</th>
                                <th className="px-6 py-3 text-center">
                                    Action
                                </th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-800/50">
                            {renderContractList(
                                groupedContracts.active,
                                'active',
                            )}
                        </tbody>
                    </table>
                </div>
            </section>

            {/* 3. Kategori Expiring Soon */}
            <section className="overflow-hidden rounded-lg border border-slate-800 bg-slate-900/20">
                <div className="flex items-center gap-3 border-b border-slate-800 bg-slate-900/60 px-6 py-4">
                    <AlertCircle className="h-5 w-5 text-orange-400" />
                    <div>
                        <h3 className="text-base font-semibold text-white">
                            Expiring Soon
                        </h3>
                        <p className="mt-0.5 text-xs text-slate-400">
                            {groupedContracts['expiring-soon'].length} dokumen
                            (kurang dari 30 hari)
                        </p>
                    </div>
                </div>
                <div className="overflow-x-auto">
                    <table className="w-full border-collapse text-left text-sm">
                        <thead className="border-b border-slate-800 bg-slate-900/40 text-xs font-semibold tracking-wider text-slate-400 uppercase">
                            <tr>
                                <th className="px-6 py-3">Contract</th>
                                <th className="px-6 py-3">Counterparty</th>
                                <th className="px-6 py-3">Status</th>
                                <th className="px-6 py-3">End Date</th>
                                <th className="px-6 py-3">Days Left</th>
                                <th className="px-6 py-3 text-center">
                                    Action
                                </th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-800/50">
                            {renderContractList(
                                groupedContracts['expiring-soon'],
                                'expiring-soon',
                            )}
                        </tbody>
                    </table>
                </div>
            </section>

            {/* 4. Kategori Expired */}
            <section className="overflow-hidden rounded-lg border border-slate-800 bg-slate-900/20">
                <div className="flex items-center gap-3 border-b border-slate-800 bg-slate-900/60 px-6 py-4">
                    <AlertCircle className="h-5 w-5 text-red-500" />
                    <div>
                        <h3 className="text-base font-semibold text-white">
                            Expired
                        </h3>
                        <p className="mt-0.5 text-xs text-slate-400">
                            {groupedContracts.expired.length} dokumen telah
                            kedaluwarsa
                        </p>
                    </div>
                </div>
                <div className="overflow-x-auto">
                    <table className="w-full border-collapse text-left text-sm">
                        <thead className="border-b border-slate-800 bg-slate-900/40 text-xs font-semibold tracking-wider text-slate-400 uppercase">
                            <tr>
                                <th className="px-6 py-3">Contract</th>
                                <th className="px-6 py-3">Counterparty</th>
                                <th className="px-6 py-3">Status</th>
                                <th className="px-6 py-3">End Date</th>
                                <th className="px-6 py-3">Days Left</th>
                                <th className="px-6 py-3 text-center">
                                    Action
                                </th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-800/50">
                            {renderContractList(
                                groupedContracts.expired,
                                'expired',
                            )}
                        </tbody>
                    </table>
                </div>
            </section>
            {/* POP-UP CHAT AI */}
            <AIChatPopup
                activeContractId={contracts && contracts.length > 0 ? contracts[0].id : null}
                activeContractName={contracts && contracts.length > 0 ? contracts[0].docName : ''}
            />
        </div>
    );
}
