import React, {useEffect, useMemo, useState} from 'react';
import {makeDeleteRequest, makeGetRequest, makePostRequest} from '@/lib/request';
import {usePage} from '@inertiajs/react';
import {notify} from '@/lib/notify';

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

    const [results, setResults] = useState<any>({data: [], current_page: 1, last_page: 1, total: 0});
    const [page, setPage] = useState<number>(1);
    const [query, setQuery] = useState<string>('');
    const [loading, setLoading] = useState<boolean>(false);
    const [active, setActive] = useState<any | null>(null);

    const fetch = async (p = page, q = query) => {
        setLoading(true);
        try {
            const params = new URLSearchParams();
            params.append('page', String(p));
            if (q) params.append('search', q);
            const res = await makeGetRequest(`/api/conflict-checks?${params.toString()}`, {token});
            const payload = res.data?.result ?? res.data ?? {};
            const list = payload?.data ?? [];
            setResults({...payload, data: Array.isArray(list) ? list : []});
        } catch (e: any) {
            notify.toastErrorMessage('Failed to load conflict checks');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetch(1, query);
    }, [query]);
    useEffect(() => {
        fetch(page, query);
    }, [page]);

    const gotoPage = (p: number) => {
        if (!results) return;
        const last = results?.last_page ?? 1;
        if (p < 1 || p > last) return;
        setPage(p);
    };

    const view = (c: any) => setActive(c);

    const approve = async (c: any) => {
        if (!confirm('Approve waiver for this conflict?')) return;
        try {
            await makePostRequest(`/api/conflict-checks/${c.id}/approve`, {}, {token});
            notify.toastSuccessMessage('Conflict approved');
            fetch(page, query);
        } catch (e: any) {
            notify.toastErrorMessage(e?.response?.data?.message || 'Failed to approve');
        }
    };

    const remove = async (c: any) => {
        if (!confirm('Delete this conflict check?')) return;
        try {
            await makeDeleteRequest(`/api/conflict-checks/${c.id}`, {token});
            notify.toastSuccessMessage('Conflict deleted');
            fetch(page, query);
        } catch (e: any) {
            notify.toastErrorMessage(e?.response?.data?.message || 'Failed to delete');
        }
    };

    const pageButtons = useMemo(() => {
        const last = results?.last_page ?? 1;
        const current = results?.current_page ?? 1;
        const pages = [];
        for (let i = 1; i <= last; i++) pages.push(i);
        return {pages, current};
    }, [results]);

    return (
        <>
            <div className="bg-white rounded-lg shadow p-6">
                <div className="flex justify-between mb-4">
                    <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search conflicts"
                           className="ti-form-input max-w-sm"/>
                </div>

                <div className="overflow-auto">
                    <table className="min-w-full divide-y divide-gray-200">
                        <thead className="bg-gray-50">
                        <tr>
                            <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Client</th>
                            <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                            <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Checked By
                            </th>
                            <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Created</th>
                            <th className="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">Actions</th>
                        </tr>
                        </thead>
                        <tbody className="bg-white divide-y divide-gray-200">
                        {loading ? (
                            <tr>
                                <td colSpan={5} className="p-6 text-center">Loading...</td>
                            </tr>
                        ) : results.data.length === 0 ? (
                            <tr>
                                <td colSpan={5} className="p-6 text-center">No conflicts found</td>
                            </tr>
                        ) : results.data.map((c: any) => (
                            <tr key={c.id}>
                                <td className="px-4 py-2 text-sm">{c.client?.name ?? '-'}</td>
                                <td className="px-4 py-2 text-sm">{c.status}</td>
                                <td className="px-4 py-2 text-sm">{c.checkedBy?.name ?? '-'}</td>
                                <td className="px-4 py-2 text-sm">{new Date(c.created_at).toLocaleDateString()}</td>
                                <td className="px-4 py-2 text-sm text-right">
                                    <div className="hs-tooltip ti-main-tooltip inline-flex gap-2">
                                        <button
                                            type="button"
                                            onClick={() => view(c)}
                                            className="hs-tooltip-toggle w-8 h-8 ti-btn rounded-full p-0 transition-none focus:outline-none ti-btn-soft-secondary"
                                            title="View"
                                        >
                                            <i className="ti ti-eye text-sm"></i>
                                        </button>

                                        {c.status !== 'waiver_approved' && (
                                            <button
                                                type="button"
                                                onClick={() => approve(c)}
                                                className="hs-tooltip-toggle w-8 h-8 ti-btn rounded-full p-0 transition-none focus:outline-none ti-btn-soft-success"
                                                title="Approve"
                                            >
                                                <i className="ti ti-check text-sm"></i>
                                            </button>
                                        )}

                                        <button
                                            type="button"
                                            onClick={() => remove(c)}
                                            className="hs-tooltip-toggle w-8 h-8 ti-btn rounded-full p-0 transition-none focus:outline-none ti-btn-soft-danger"
                                            title="Delete"
                                        >
                                            <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 {results.data?.length} of {results.total} items
                    </div>
                    <div className="flex items-center gap-2">
                        <button disabled={results.current_page <= 1}
                                onClick={() => gotoPage((results.current_page ?? 1) - 1)}
                                className="px-2 py-1 border rounded">Prev
                        </button>
                        {pageButtons.pages.map(p => (
                            <button key={p} onClick={() => gotoPage(p)}
                                    className={`px-2 py-1 border rounded ${p === pageButtons.current ? 'bg-indigo-600 text-white' : ''}`}>{p}</button>
                        ))}
                        <button disabled={(results.current_page ?? 1) >= (results.last_page ?? 1)}
                                onClick={() => gotoPage((results.current_page ?? 1) + 1)}
                                className="px-2 py-1 border rounded">Next
                        </button>
                    </div>
                </div>
            </div>

            {/* View modal */}
            {active && (
                <div role="dialog" aria-modal="true"
                     className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
                    <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[80vh] overflow-auto">
                        <div className="flex items-center justify-between px-5 py-4 border-b border-gray-200">
                            <h3 className="text-base font-semibold text-gray-800">Conflict #{active.id}</h3>
                            <button
                                type="button"
                                className="p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition-colors"
                                onClick={() => setActive(null)}
                                aria-label="Close"
                            >
                                <i className="ri ri-close-line text-lg"></i>
                            </button>
                        </div>

                        <div className="px-5 py-5 space-y-4">
                            <p><strong>Client:</strong> {active.client?.name}</p>
                            <p><strong>Status:</strong> {active.status}</p>
                            <p className="mt-3"><strong>Notes</strong></p>
                            <div className="prose max-w-none">{active.notes ?? '-'}</div>
                            <pre
                                className="mt-3 bg-gray-50 p-3 rounded text-sm overflow-auto">{JSON.stringify(active.conflict_details, null, 2)}</pre>
                        </div>

                        <div className="flex items-center justify-end gap-2 px-5 py-4 border-t border-gray-200">
                            <button onClick={() => setActive(null)}
                                    className="px-4 py-2 text-sm text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">Close
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </>
    );
}
