import AppPageHeader from "@/components/AppPageHeader";
import React, {useEffect, useState} from "react";
import Create from "@/Pages/ClientProfile/Create";
import {usePage, Link} from "@inertiajs/react";
import {makeGetRequest} from "@/lib/request";

export default function Index(): JSX.Element {
    const { auth } = usePage<{ auth: { user: any } }>().props;
    const token = auth?.user?.token ?? auth?.user?.api_token ?? undefined;

    const [clients, setClients] = useState<any[]>([]);
    const [page, setPage] = useState<number>(1);
    const [query, setQuery] = useState<string>("");
    const [statusFilter, _setStatusFilter] = useState<string>("");
    const [meta, setMeta] = useState<any | null>(null);
    const [loading, setLoading] = useState<boolean>(false);
    const [createOpen, setCreateOpen] = useState<boolean>(false);
    const [selectedClient, setSelectedClient] = useState<any | null>(null);

    async function fetchClients(p = page, q = query, status = statusFilter) {
        try {
            setLoading(true);
            const params = new URLSearchParams();
            params.append("page", String(p));
            if (q) params.append("search", q);
            if (status) params.append("status", status);
            const url = `/api/clients?${params.toString()}`;
            const res = await makeGetRequest(url, { token });
            const payload = res.data?.result ?? res.data ?? {};

            // payload may be either a paginated object ({ data, current_page, last_page, total, per_page })
            // or an object with { data: [...] , meta: { current_page, last_page, total } }
            const list = payload?.data ?? [];
            setClients(Array.isArray(list) ? list : []);

            // Normalize pagination meta so UI can rely on current_page/last_page/total
            const normalizedMeta = payload?.meta
                ? payload.meta
                : (payload && payload.data ? {
                    current_page: payload.current_page ?? payload.currentPage ?? 1,
                    last_page: payload.last_page ?? payload.lastPage ?? 1,
                    total: payload.total ?? 0,
                    per_page: payload.per_page ?? payload.perPage ?? list.length,
                } : null);

            setMeta(normalizedMeta);
        } catch (e) {
            console.warn("fetchClients error", e);
        } finally {
            setLoading(false);
        }
    }

    // initial load and when page/status changes
    useEffect(() => {
        fetchClients(page, query, statusFilter);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [page, statusFilter]);

    // debounce search
    useEffect(() => {
        const t = setTimeout(() => {
            setPage(1);
            fetchClients(1, query, statusFilter);
        }, 400);
        return () => clearTimeout(t);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [query]);

    // refresh when a client is created elsewhere
    useEffect(() => {
        function onClientCreated() {
            setPage(1);
            fetchClients(1, "", "");
        }
        window.addEventListener("client:created", onClientCreated as EventListener);

        function onClientUpdated() {
            // refresh current page when a client is updated
            fetchClients(1, query, statusFilter);
        }
        window.addEventListener("client:updated", onClientUpdated as EventListener);

        return () => {
            window.removeEventListener("client:created", onClientCreated as EventListener);
            window.removeEventListener("client:updated", onClientUpdated as EventListener);
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    function gotoPage(p: number) {
        if (!meta) return;
        const last = meta?.last_page ?? meta?.lastPage ?? null;
        if (last && (p < 1 || p > last)) return;
        setPage(p);
    }

    return (
        <>
            {/* Start::row-1 */}
            <div className="grid grid-cols-12 gap-6">
                {/* Main area now occupies full width so table can use 100% */}
                <div className="col-span-12">
                    <div className="box">
                        <div className="box-body">
                            <div className="flex justify-between mb-5">
                                <div className="">
                                    <div className="relative sm:max-w-xs max-w-[210px]">
                                        <label htmlFor="hs-table-search" className="sr-only">Search</label>
                                        <div
                                            className="absolute inset-y-0 end-0 flex items-center pointer-events-none pe-4">
                                            <i className="ti ti-search"></i>
                                        </div>
                                        <input
                                            type="text"
                                            name="hs-table-search"
                                            id="hs-table-search"
                                            value={query}
                                            onChange={(e) => setQuery(e.target.value)}
                                            className="p-2 pe-10 ti-form-input"
                                            placeholder="Search clients"
                                        />
                                    </div>
                                </div>
                                <div className="">
                                    <button
                                        type="button"
                                        className="ti-btn ti-btn-primary py-2 px-3 whitespace-nowrap"
                                        onClick={() => setCreateOpen(true)}
                                    >
                                        <i className="ri ri-edit-line mr-2"></i> Add Client
                                    </button>
                                </div>
                            </div>
                            <div className="rounded-sm overflow-auto todo-table w-full">
                                <table className="ti-custom-table ti-custom-table-head whitespace-nowrap w-full">
                                    <thead className="bg-gray-100 dark:bg-bodybg">
                                    <tr>
                                        <th scope="col" className="dark:text-white/70">Name</th>
                                        <th scope="col" className="dark:text-white/70">Email</th>
                                        <th scope="col" className="dark:text-white/70">Phone</th>
                                        <th scope="col" className="dark:text-white/70">Type</th>
                                        <th scope="col" className="dark:text-white/70">Status</th>
                                        <th scope="col" className="dark:text-white/70 min-w-[160px]">Created</th>
                                        <th scope="col" className="!text-end dark:text-white/70">Action</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    {loading ? (
                                        <tr>
                                            <td colSpan={7} className="text-center py-8">Loading...</td>
                                        </tr>
                                    ) : clients.length === 0 ? (
                                        <tr>
                                            <td colSpan={7} className="text-center py-8">No clients found.</td>
                                        </tr>
                                    ) : (
                                        clients.map((client: any) => (
                                            <tr key={client.id} className="todo-box">
                                                <td>
                                                    <Link href={`/clients/${client.id}`} className="text-sm font-semibold w-52 truncate text-indigo-600 hover:underline block">{client.name}</Link>
                                                </td>
                                                <td>{client.email ?? '-'}</td>
                                                <td>{client.phone ?? '-'}</td>
                                                <td>{client.client_type?.toUpperCase() ?? '-'}</td>
                                                <td>{client.status ? <span className="text-success">{client.status}</span> : '-'}</td>
                                                <td>
                                                    <div className="flex -space-x-2 rtl:space-x-reverse">
                                                        <span className="text-sm">{client.created_at ? new Date(client.created_at).toLocaleDateString() : '-'}</span>
                                                    </div>
                                                </td>
                                                <td className="text-end font-medium">
                                                                                    <div className="hs-tooltip ti-main-tooltip inline-flex gap-2">
                                                                                        <button
                                                                                            type="button"
                                                                                            className="hs-tooltip-toggle w-8 h-8 ti-btn rounded-full p-0 transition-none focus:outline-none ti-btn-soft-secondary"
                                                                                            onClick={() => { setSelectedClient(client); setCreateOpen(true); }}
                                                                                            title="Edit client"
                                                                                        >
                                                                                            <i className="ti ti-pencil"></i>
                                                                                        </button>
                                                        <button type="button" className="todo-remove hs-tooltip-toggle w-8 h-8 ti-btn rounded-full p-0 transition-none focus:outline-none ti-btn-soft-danger">
                                                            <i className="ti ti-trash"></i>
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                        ))
                                    )}
                                    </tbody>
                                </table>
                            </div>

                            <div className="flex items-center justify-between mt-4">
                                <div className="text-sm text-gray-600">showing {clients?.length} of {meta?.total ?? 0} items</div>
                                <div className="flex items-center gap-2">
                                    <button
                                        type="button"
                                        disabled={(meta?.current_page ?? 1) <= 1}
                                        onClick={() => gotoPage((meta?.current_page ?? 1) - 1)}
                                        className="px-2 py-1 border rounded disabled:opacity-40 disabled:cursor-not-allowed"
                                    >
                                        Prev
                                    </button>

                                    {Array.from({ length: meta?.last_page ?? 1 }).map((_, i) => {
                                        const p = i + 1;
                                        return (
                                            <button
                                                key={p}
                                                type="button"
                                                onClick={() => gotoPage(p)}
                                                className={`px-2 py-1 border rounded ${p === (meta?.current_page ?? page) ? 'bg-indigo-600 text-white' : ''}`}
                                            >
                                                {p}
                                            </button>
                                        );
                                    })}

                                    <button
                                        type="button"
                                        disabled={(meta?.current_page ?? 1) >= (meta?.last_page ?? 1)}
                                        onClick={() => gotoPage((meta?.current_page ?? 1) + 1)}
                                        className="px-2 py-1 border rounded disabled:opacity-40 disabled:cursor-not-allowed"
                                    >
                                        Next
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            {/* End::row-1 */}
            <Create
                open={createOpen}
                onClose={() => { setCreateOpen(false); setSelectedClient(null); }}
                client={selectedClient ?? undefined}
                mode={selectedClient ? 'edit' : 'create'}
            />
        </>
    );
}
