import { useState, useMemo } from 'react';
import { router, usePage, Head, Link } from '@inertiajs/react';
import { Search, Plus, Bell } from 'lucide-react';
import { ContractsTable, Contract } from '../components/contract-table';
import AIChatPopup from '../components/chat-popup';

export default function ContractList({ contracts }: any) {
    const { props } = usePage();
    const contractList = contracts.data;
    const auth = props.auth as any;

    const [searchTerm, setSearchTerm] = useState('');
    const [filterType, setFilterType] = useState('all');
    const [filterSigned, setFilterSigned] = useState('all');
    const [sortBy, setSortBy] = useState('date');

    const handleNavigateToUpload = () => {
        router.get('/contract-form');
    };

    const handleDeleteContract = (contractId: string | number) => {
        if (confirm('Yakin ingin menghapus kontrak ini?')) {
            router.delete(`/contracts/${contractId}`, {
                preserveScroll: true,
            });
        }
    };

    const docTypes = useMemo(() => {
        const types = new Set(
            contractList.map((c: any) => (c.id ? 'Operational' : '')),
        );
        return Array.from(types).filter(Boolean);
    }, [contractList]);

    const filteredContracts = useMemo(() => {
        let filtered = [...contractList];

        if (searchTerm) {
            const term = searchTerm.toLowerCase();
            filtered = filtered.filter(
                (c: any) =>
                    c.docName?.toLowerCase().includes(term) ||
                    c.docNumber?.toLowerCase().includes(term) ||
                    c.counterParty?.toLowerCase().includes(term) ||
                    c.internalParty?.toLowerCase().includes(term),
            );
        }

        if (filterSigned !== 'all') {
            filtered = filtered.filter((c: any) => {
                const isSignedBool =
                    c.isSigned === true ||
                    c.isSigned === 1 ||
                    c.isSigned === '1' ||
                    c.isSigned === 'true';
                return filterSigned === 'signed' ? isSignedBool : !isSignedBool;
            });
        }

        filtered.sort((a: any, b: any) => {
            if (sortBy === 'date') {
                return (
                    new Date(b.created_at).getTime() -
                    new Date(a.created_at).getTime()
                );
            } else {
                return (Number(b.value) || 0) - (Number(a.value) || 0);
            }
        });

        return filtered;
    }, [contractList, searchTerm, filterSigned, sortBy]);

    return (
        <>
            <Head title="Contracts Table - Scuto Legal" />

            <div className="flex min-h-screen flex-1 flex-col bg-slate-950 text-white">
                {/* HEADER SEARCH BAR */}
                <header className="sticky top-0 z-40 border-b border-slate-800 bg-slate-900/50 backdrop-blur">
                    <div className="flex items-center justify-between px-8 py-4">
                        <div className="max-w-md flex-1">
                            <div className="relative">
                                <Search className="absolute top-1/2 left-3 h-5 w-5 -translate-y-1/2 text-slate-500" />
                                <input
                                    type="text"
                                    placeholder="Search contracts, parties..."
                                    value={searchTerm}
                                    onChange={(e) =>
                                        setSearchTerm(e.target.value)
                                    }
                                    className="w-full rounded-lg border border-slate-800 bg-slate-950 py-2 pr-4 pl-10 text-sm text-white placeholder-slate-500 focus:border-blue-500 focus:outline-none"
                                />
                            </div>
                        </div>

                        <div className="flex items-center gap-4">
                            <button
                                onClick={handleNavigateToUpload}
                                className="inline-flex items-center gap-2 rounded-lg bg-orange-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-orange-700"
                            >
                                <Plus className="h-4 w-4" />
                                New contract
                            </button>

                            <div className="flex h-8 w-8 items-center justify-center rounded-full bg-orange-600 text-sm font-bold text-white">
                                {auth?.user?.name
                                    ? auth.user.name[0].toUpperCase()
                                    : 'D'}
                            </div>
                        </div>
                    </div>
                </header>

                {/* FILTER CONTROLS & TABLE BOX */}
                <main className="flex-1 space-y-6 overflow-auto p-8">
                    <div>
                        <h1 className="text-3xl font-bold text-white">
                            Contracts Table
                        </h1>
                        <p className="mt-1 text-slate-400">
                            Manage, filter, and track all your operational
                            contract details in one secure place.
                        </p>
                    </div>

                    {/* Tampilan Wrapper Box Filter */}
                    <div className="rounded-lg border border-slate-800 bg-slate-900/40 p-6">
                        <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
                            <div>
                                <label className="block text-xs font-medium tracking-wider text-slate-400 uppercase">
                                    Signature Status
                                </label>
                                <select
                                    value={filterSigned}
                                    onChange={(e) =>
                                        setFilterSigned(e.target.value)
                                    }
                                    className="mt-1.5 w-full rounded-lg border border-slate-800 bg-slate-950 px-4 py-2 text-sm text-white focus:border-blue-500 focus:outline-none"
                                >
                                    <option value="all">All Status</option>
                                    <option value="signed">Active</option>
                                    <option value="unsigned">Pending</option>
                                </select>
                            </div>

                            <div>
                                <label className="block text-xs font-medium tracking-wider text-slate-400 uppercase">
                                    Sort By
                                </label>
                                <select
                                    value={sortBy}
                                    onChange={(e) => setSortBy(e.target.value)}
                                    className="mt-1.5 w-full rounded-lg border border-slate-800 bg-slate-950 px-4 py-2 text-sm text-white focus:border-blue-500 focus:outline-none"
                                >
                                    <option value="date">
                                        Upload Date (Newest)
                                    </option>
                                    <option value="value">
                                        Contract Value (Highest)
                                    </option>
                                </select>
                            </div>
                        </div>
                        <p className="mt-4 text-xs text-slate-500">
                            Showing {filteredContracts.length} of{' '}
                            {contracts.total || contractList.length} contracts
                        </p>
                    </div>

                    <ContractsTable
                        contracts={filteredContracts}
                        onDelete={handleDeleteContract}
                    />
                </main>
                {/* POP-UP CHAT AI */}
                <AIChatPopup
                    activeContractId={contracts && contracts.length > 0 ? contracts[0].id : null}
                    activeContractName={contracts && contracts.length > 0 ? contracts[0].docName : ''}
                />
            </div>
        </>
    );
}
