import React, {useEffect, useMemo, useState} from 'react';
import {usePage} from '@inertiajs/react';
import MainLayout from '@/layouts/MainLayout';
import AppPageHeader from '@/components/AppPageHeader';
import {makeGetRequest, makePostRequest, makePutRequest} from '@/lib/request';
import {notify} from '@/lib/notify';

const TASK_TYPES = [
    {value: 'general', label: 'General'},
    {value: 'deadline', label: 'Deadline'},
    {value: 'filing', label: 'Filing'},
    {value: 'hearing', label: 'Hearing'},
    {value: 'research', label: 'Research'},
    {value: 'client_meeting', label: 'Client meeting'},
    {value: 'discovery', label: 'Discovery'},
];

const STATUS_OPTIONS = [
    {value: '', label: 'All statuses'},
    {value: 'draft', label: 'Draft'},
    {value: 'pending', label: 'Pending approval'},
    {value: 'approved', label: 'Approved'},
    {value: 'invoiced', label: 'Invoiced'},
];

function formatDuration(minutes: number): string {
    const h = Math.floor(minutes / 60);
    const m = minutes % 60;
    if (h === 0) return `${m}m`;
    if (m === 0) return `${h}h`;
    return `${h}h ${m}m`;
}

function hoursToMinutes(hours: number): number {
    return Math.ceil((hours * 60) / 6) * 6;
}

function minutesToHours(minutes: number): number {
    return Math.round((minutes / 60) * 10) / 10;
}

function todayIso(): string {
    return new Date().toISOString().slice(0, 10);
}

function statusClass(status: string): string {
    switch (status) {
        case 'draft':
            return 'text-warning';
        case 'pending':
            return 'text-info';
        case 'approved':
            return 'text-success';
        case 'invoiced':
            return 'text-gray-500';
        default:
            return '';
    }
}

function statusLabel(status: string): string {
    return status.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
}

interface FormState {
    client_matter_id: number | '';
    entry_date: string;
    duration_hours: number | '';
    description: string;
    task_type: string;
    billable: boolean;
    hourly_rate: number | '';
}

const emptyForm = (): FormState => ({
    client_matter_id: '',
    entry_date: todayIso(),
    duration_hours: 0.1,
    description: '',
    task_type: 'general',
    billable: true,
    hourly_rate: '',
});

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

    const [entries, setEntries] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);
    const [page, setPage] = useState(1);
    const [meta, setMeta] = useState<any>(null);
    const [statusFilter, setStatusFilter] = useState('');
    const [selectedIds, setSelectedIds] = useState<number[]>([]);
    const [batchSubmitting, setBatchSubmitting] = useState(false);

    const [formOpen, setFormOpen] = useState(false);
    const [editingEntry, setEditingEntry] = useState<any | null>(null);
    const [form, setForm] = useState<FormState>(emptyForm());
    const [formErrors, setFormErrors] = useState<Record<string, string[]>>({});
    const [submitting, setSubmitting] = useState(false);

    const [matters, setMatters] = useState<any[]>([]);
    const [matterQuery, setMatterQuery] = useState('');
    const [showMatterDropdown, setShowMatterDropdown] = useState(false);
    const [filteredMatters, setFilteredMatters] = useState<any[]>([]);

    const [viewEntry, setViewEntry] = useState<any | null>(null);

    useEffect(() => {
        fetchEntries();
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [page, statusFilter, token]);

    useEffect(() => {
        fetchMatters();
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [token]);

    useEffect(() => {
        const t = setTimeout(() => setPage(1), 300);
        return () => clearTimeout(t);
    }, [statusFilter]);

    useEffect(() => {
        if (!formOpen) return;
        if (editingEntry) {
            setForm({
                client_matter_id: editingEntry.client_matter_id ?? '',
                entry_date: editingEntry.entry_date?.slice?.(0, 10) ?? editingEntry.entry_date ?? todayIso(),
                duration_hours: minutesToHours(editingEntry.duration_minutes ?? 6),
                description: editingEntry.description ?? '',
                task_type: editingEntry.task_type ?? 'general',
                billable: editingEntry.billable ?? true,
                hourly_rate: editingEntry.hourly_rate ?? '',
            });
            const m = editingEntry.matter;
            setMatterQuery(m ? `${m.reference_number ?? ''} — ${m.matter_type ?? ''}`.trim() : '');
        } else {
            setForm(emptyForm());
            setMatterQuery('');
        }
        setFormErrors({});
    }, [formOpen, editingEntry]);

    async function fetchMatters() {
        try {
            const res = await makeGetRequest('/api/matters?per_page=200', {token});
            const payload = res.data?.result ?? res.data ?? {};
            const list = payload?.data ?? payload ?? [];
            setMatters(Array.isArray(list) ? list : []);
        } catch {
            /* ignore */
        }
    }

    async function fetchEntries() {
        setLoading(true);
        try {
            const params = new URLSearchParams({page: String(page)});
            if (statusFilter) params.append('status', statusFilter);
            const res = await makeGetRequest(`/api/time-entries?${params}`, {token});
            const payload = res.data?.result ?? res.data ?? {};
            const list = payload?.data ?? payload ?? [];
            setEntries(Array.isArray(list) ? list : []);
            setMeta(payload?.meta ?? (payload?.data ? {
                current_page: payload.current_page ?? page,
                last_page: payload.last_page ?? 1,
                total: payload.total ?? 0,
            } : null));
            setSelectedIds([]);
        } catch (e: any) {
            notify.toastErrorMessage(e?.response?.data?.message || 'Failed to load time entries');
        } finally {
            setLoading(false);
        }
    }

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

    const openCreate = () => {
        setEditingEntry(null);
        setFormOpen(true);
    };

    const openEdit = (entry: any) => {
        setEditingEntry(entry);
        setFormOpen(true);
    };

    const closeForm = () => {
        setFormOpen(false);
        setEditingEntry(null);
    };

    const filterMatters = (q: string) => {
        const needle = q.trim().toLowerCase();
        if (!needle) return matters.slice(0, 50);
        return matters.filter((m: any) => {
            const ref = (m.reference_number ?? '').toLowerCase();
            const type = (m.matter_type ?? '').toLowerCase();
            const client = (m.client?.name ?? '').toLowerCase();
            return ref.includes(needle) || type.includes(needle) || client.includes(needle);
        }).slice(0, 50);
    };

    const submitForm = async (e: React.FormEvent) => {
        e.preventDefault();
        setFormErrors({});

        const validation: Record<string, string[]> = {};
        if (!form.client_matter_id) validation.client_matter_id = ['Matter is required'];
        if (!form.entry_date) validation.entry_date = ['Date is required'];
        if (!form.duration_hours || Number(form.duration_hours) <= 0) {
            validation.duration_minutes = ['Duration must be greater than zero'];
        }
        if ((form.description ?? '').trim().length < 10) {
            validation.description = ['Description must be at least 10 characters'];
        }
        if (Object.keys(validation).length) {
            setFormErrors(validation);
            return;
        }

        const payload: Record<string, any> = {
            client_matter_id: form.client_matter_id,
            entry_date: form.entry_date,
            duration_minutes: hoursToMinutes(Number(form.duration_hours)),
            description: form.description.trim(),
            task_type: form.task_type || 'general',
            billable: form.billable,
        };
        if (form.hourly_rate !== '') payload.hourly_rate = Number(form.hourly_rate);

        setSubmitting(true);
        try {
            if (editingEntry) {
                await makePutRequest(`/api/time-entries/${editingEntry.id}`, payload, {token});
                notify.toastSuccessMessage('Time entry updated');
            } else {
                await makePostRequest('/api/time-entries', payload, {token});
                notify.toastSuccessMessage('Time entry created');
            }
            closeForm();
            fetchEntries();
        } catch (err: any) {
            const resp = err?.response?.data;
            if (resp?.errors) {
                setFormErrors(resp.errors);
            } else {
                notify.toastErrorMessage(resp?.message || 'Failed to save time entry');
            }
        } finally {
            setSubmitting(false);
        }
    };

    const submitForApproval = async (entry: any) => {
        if (!confirm('Submit this entry for approval?')) return;
        try {
            await makePostRequest(`/api/time-entries/${entry.id}/submit-for-approval`, {}, {token});
            notify.toastSuccessMessage('Submitted for approval');
            fetchEntries();
        } catch (e: any) {
            notify.toastErrorMessage(e?.response?.data?.message || 'Failed to submit');
        }
    };

    const approveEntry = async (entry: any) => {
        if (!confirm('Approve this time entry?')) return;
        try {
            await makePostRequest(`/api/time-entries/${entry.id}/approve`, {}, {token});
            notify.toastSuccessMessage('Time entry approved');
            fetchEntries();
        } catch (e: any) {
            notify.toastErrorMessage(e?.response?.data?.message || 'Failed to approve');
        }
    };

    const rejectEntry = async (entry: any) => {
        const reason = prompt('Reason for rejection (required):');
        if (!reason?.trim()) return;
        try {
            await makePostRequest(`/api/time-entries/${entry.id}/reject`, {reason: reason.trim()}, {token});
            notify.toastSuccessMessage('Time entry rejected');
            fetchEntries();
        } catch (e: any) {
            notify.toastErrorMessage(e?.response?.data?.message || 'Failed to reject');
        }
    };

    const batchApprove = async () => {
        if (selectedIds.length === 0) return;
        if (!confirm(`Approve ${selectedIds.length} selected entr${selectedIds.length === 1 ? 'y' : 'ies'}?`)) return;
        setBatchSubmitting(true);
        try {
            const res = await makePostRequest('/api/time-entries/batch-approve', {ids: selectedIds}, {token});
            const count = res.data?.result?.approved ?? res.data?.approved ?? selectedIds.length;
            notify.toastSuccessMessage(`${count} entr${count === 1 ? 'y' : 'ies'} approved`);
            fetchEntries();
        } catch (e: any) {
            notify.toastErrorMessage(e?.response?.data?.message || 'Batch approve failed');
        } finally {
            setBatchSubmitting(false);
        }
    };

    const toggleSelect = (id: number) => {
        setSelectedIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
    };

    const toggleSelectAllPending = () => {
        const pendingIds = entries.filter((e) => e.status === 'pending').map((e) => e.id);
        const allSelected = pendingIds.length > 0 && pendingIds.every((id) => selectedIds.includes(id));
        setSelectedIds(allSelected ? [] : pendingIds);
    };

    const pageSummary = useMemo(() => {
        const billable = entries.filter((e) => e.billable).reduce((s, e) => s + (e.duration_minutes ?? 0), 0);
        const nonBillable = entries.filter((e) => !e.billable).reduce((s, e) => s + (e.duration_minutes ?? 0), 0);
        return {billable, nonBillable};
    }, [entries]);

    const hasPendingOnPage = entries.some((e) => e.status === 'pending');

    return (
        <MainLayout>
            <AppPageHeader title="Time Tracking" subtitle="Time & Billing"/>

            <div className="grid grid-cols-12 gap-6 mb-6">
                <div className="col-span-12 sm:col-span-4">
                    <div className="box">
                        <div className="box-body">
                            <p className="text-sm text-gray-500 mb-1">Billable</p>
                            <p className="text-2xl font-semibold">{formatDuration(pageSummary.billable)}</p>
                        </div>
                    </div>
                </div>
                <div className="col-span-12 sm:col-span-4">
                    <div className="box">
                        <div className="box-body">
                            <p className="text-sm text-gray-500 mb-1">Non-billable</p>
                            <p className="text-2xl font-semibold">{formatDuration(pageSummary.nonBillable)}</p>
                        </div>
                    </div>
                </div>
                <div className="col-span-12 sm:col-span-4">
                    <div className="box">
                        <div className="box-body">
                            <p className="text-sm text-gray-500 mb-1">Total entries</p>
                            <p className="text-2xl font-semibold">{meta?.total ?? entries.length}</p>
                        </div>
                    </div>
                </div>
            </div>

            <div className="grid grid-cols-12 gap-6">
                <div className="col-span-12">
                    <div className="box">
                        <div className="box-body">
                            <div className="flex flex-wrap justify-between gap-4 mb-5">
                                <div className="flex flex-wrap items-center gap-3">
                                    <select
                                        className="ti-form-input w-auto"
                                        value={statusFilter}
                                        onChange={(e) => setStatusFilter(e.target.value)}
                                    >
                                        {STATUS_OPTIONS.map((o) => (
                                            <option key={o.value} value={o.value}>{o.label}</option>
                                        ))}
                                    </select>
                                    {selectedIds.length > 0 && (
                                        <button
                                            type="button"
                                            className="ti-btn ti-btn-success py-2 px-3"
                                            disabled={batchSubmitting}
                                            onClick={batchApprove}
                                        >
                                            {batchSubmitting ? 'Approving…' : `Approve selected (${selectedIds.length})`}
                                        </button>
                                    )}
                                </div>
                                <button
                                    type="button"
                                    className="ti-btn ti-btn-primary py-2 px-3 whitespace-nowrap"
                                    onClick={openCreate}
                                >
                                    <i className="ri ri-add-line mr-2"></i> Log Time
                                </button>
                            </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>
                                        {hasPendingOnPage && (
                                            <th scope="col" className="dark:text-white/70 w-10">
                                                <input
                                                    type="checkbox"
                                                    aria-label="Select all pending"
                                                    onChange={toggleSelectAllPending}
                                                    checked={
                                                        entries.filter((e) => e.status === 'pending').length > 0 &&
                                                        entries.filter((e) => e.status === 'pending').every((e) => selectedIds.includes(e.id))
                                                    }
                                                />
                                            </th>
                                        )}
                                        <th scope="col" className="dark:text-white/70">Date</th>
                                        <th scope="col" className="dark:text-white/70">Matter</th>
                                        <th scope="col" className="dark:text-white/70">User</th>
                                        <th scope="col" className="dark:text-white/70">Duration</th>
                                        <th scope="col" className="dark:text-white/70 min-w-[200px]">Description</th>
                                        <th scope="col" className="dark:text-white/70">Task</th>
                                        <th scope="col" className="dark:text-white/70">Billable</th>
                                        <th scope="col" className="dark:text-white/70">Status</th>
                                        <th scope="col" className="!text-end dark:text-white/70">Action</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    {loading ? (
                                        <tr>
                                            <td colSpan={hasPendingOnPage ? 10 : 9} className="text-center py-8">Loading…</td>
                                        </tr>
                                    ) : entries.length === 0 ? (
                                        <tr>
                                            <td colSpan={hasPendingOnPage ? 10 : 9} className="text-center py-8">No time entries found.</td>
                                        </tr>
                                    ) : (
                                        entries.map((entry) => (
                                            <tr key={entry.id}>
                                                {hasPendingOnPage && (
                                                    <td>
                                                        {entry.status === 'pending' ? (
                                                            <input
                                                                type="checkbox"
                                                                checked={selectedIds.includes(entry.id)}
                                                                onChange={() => toggleSelect(entry.id)}
                                                                aria-label={`Select entry ${entry.id}`}
                                                            />
                                                        ) : null}
                                                    </td>
                                                )}
                                                <td>{entry.entry_date ? new Date(entry.entry_date).toLocaleDateString() : '—'}</td>
                                                <td>
                                                    <div className="text-sm font-medium">{entry.matter?.reference_number ?? '—'}</div>
                                                    <div className="text-xs text-gray-500">{entry.matter?.matter_type ?? ''}</div>
                                                </td>
                                                <td>{entry.user?.name ?? '—'}</td>
                                                <td>{formatDuration(entry.duration_minutes ?? 0)}</td>
                                                <td className="max-w-xs truncate" title={entry.description}>{entry.description}</td>
                                                <td>{entry.task_type ? statusLabel(entry.task_type) : '—'}</td>
                                                <td>{entry.billable ? 'Yes' : 'No'}</td>
                                                <td><span className={statusClass(entry.status)}>{statusLabel(entry.status)}</span></td>
                                                <td className="text-end font-medium">
                                                    <div className="inline-flex gap-2">
                                                        <button
                                                            type="button"
                                                            className="w-8 h-8 ti-btn rounded-full p-0 ti-btn-soft-secondary"
                                                            title="View"
                                                            onClick={() => setViewEntry(entry)}
                                                        >
                                                            <i className="ti ti-eye"></i>
                                                        </button>
                                                        {entry.status === 'draft' && (
                                                            <>
                                                                <button
                                                                    type="button"
                                                                    className="w-8 h-8 ti-btn rounded-full p-0 ti-btn-soft-secondary"
                                                                    title="Edit"
                                                                    onClick={() => openEdit(entry)}
                                                                >
                                                                    <i className="ti ti-pencil"></i>
                                                                </button>
                                                                <button
                                                                    type="button"
                                                                    className="w-8 h-8 ti-btn rounded-full p-0 ti-btn-soft-info"
                                                                    title="Submit for approval"
                                                                    onClick={() => submitForApproval(entry)}
                                                                >
                                                                    <i className="ti ti-send"></i>
                                                                </button>
                                                            </>
                                                        )}
                                                        {entry.status === 'pending' && (
                                                            <>
                                                                <button
                                                                    type="button"
                                                                    className="w-8 h-8 ti-btn rounded-full p-0 ti-btn-soft-success"
                                                                    title="Approve"
                                                                    onClick={() => approveEntry(entry)}
                                                                >
                                                                    <i className="ti ti-check"></i>
                                                                </button>
                                                                <button
                                                                    type="button"
                                                                    className="w-8 h-8 ti-btn rounded-full p-0 ti-btn-soft-danger"
                                                                    title="Reject"
                                                                    onClick={() => rejectEntry(entry)}
                                                                >
                                                                    <i className="ti ti-x"></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 {entries.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"
                                    >
                                        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"
                                    >
                                        Next
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Create / Edit modal */}
            {formOpen && (
                <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-lg max-h-[90vh] overflow-auto">
                        <form onSubmit={submitForm} noValidate>
                            <div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 sticky top-0 bg-white z-10">
                                <h3 className="text-base font-semibold text-gray-800">
                                    {editingEntry ? 'Edit Time Entry' : 'Log Time'}
                                </h3>
                                <button type="button" className="p-1.5 text-gray-400 hover:text-gray-600 rounded" onClick={closeForm} aria-label="Close">
                                    <i className="ri ri-close-line text-lg"></i>
                                </button>
                            </div>

                            <div className="px-5 py-5 space-y-4">
                                {!editingEntry ? (
                                    <div className="relative">
                                        <label className="ti-form-label">Matter</label>
                                        <input
                                            type="text"
                                            className="ti-form-input"
                                            placeholder="Search by reference, type, or client"
                                            value={matterQuery}
                                            onChange={(e) => {
                                                setMatterQuery(e.target.value);
                                                setShowMatterDropdown(true);
                                                setFilteredMatters(filterMatters(e.target.value));
                                                setForm((f) => ({...f, client_matter_id: ''}));
                                            }}
                                            onFocus={() => {
                                                setShowMatterDropdown(true);
                                                setFilteredMatters(filterMatters(matterQuery));
                                            }}
                                            onBlur={() => setTimeout(() => setShowMatterDropdown(false), 150)}
                                        />
                                        {showMatterDropdown && (
                                            <ul className="absolute z-20 left-0 right-0 bg-white border rounded mt-1 max-h-52 overflow-auto shadow">
                                                {filteredMatters.length === 0 && (
                                                    <li className="px-3 py-2 text-xs text-gray-500">No matters found</li>
                                                )}
                                                {filteredMatters.map((m: any) => (
                                                    <li
                                                        key={m.id}
                                                        className="px-3 py-2 hover:bg-gray-100 cursor-pointer text-sm"
                                                        onMouseDown={(e) => e.preventDefault()}
                                                        onClick={() => {
                                                            setForm((f) => ({...f, client_matter_id: m.id}));
                                                            setMatterQuery(`${m.reference_number ?? ''} — ${m.matter_type ?? ''}${m.client?.name ? ` (${m.client.name})` : ''}`);
                                                            setShowMatterDropdown(false);
                                                        }}
                                                    >
                                                        <div className="font-medium">{m.reference_number} — {m.matter_type}</div>
                                                        {m.client?.name && <div className="text-xs text-gray-500">{m.client.name}</div>}
                                                    </li>
                                                ))}
                                            </ul>
                                        )}
                                        {formErrors.client_matter_id && (
                                            <p className="text-sm text-red-600 mt-1">{formErrors.client_matter_id[0]}</p>
                                        )}
                                    </div>
                                ) : (
                                    <div>
                                        <label className="ti-form-label">Matter</label>
                                        <p className="text-sm text-gray-700 py-2">
                                            {editingEntry.matter?.reference_number ?? '—'} — {editingEntry.matter?.matter_type ?? ''}
                                        </p>
                                    </div>
                                )}

                                <div>
                                    <label className="ti-form-label">Date</label>
                                    <input
                                        type="date"
                                        className="ti-form-input"
                                        max={todayIso()}
                                        value={form.entry_date}
                                        onChange={(e) => setForm((f) => ({...f, entry_date: e.target.value}))}
                                    />
                                    {formErrors.entry_date && <p className="text-sm text-red-600 mt-1">{formErrors.entry_date[0]}</p>}
                                </div>

                                <div>
                                    <label className="ti-form-label">Duration (hours)</label>
                                    <input
                                        type="number"
                                        step="0.1"
                                        min="0.1"
                                        className="ti-form-input"
                                        value={form.duration_hours}
                                        onChange={(e) => setForm((f) => ({...f, duration_hours: e.target.value === '' ? '' : Number(e.target.value)}))}
                                    />
                                    <p className="text-xs text-gray-500 mt-1">Rounded to nearest 6 minutes (0.1 hr)</p>
                                    {formErrors.duration_minutes && (
                                        <p className="text-sm text-red-600 mt-1">{formErrors.duration_minutes[0]}</p>
                                    )}
                                </div>

                                <div>
                                    <label className="ti-form-label">Description</label>
                                    <textarea
                                        className="ti-form-input"
                                        rows={3}
                                        value={form.description}
                                        onChange={(e) => setForm((f) => ({...f, description: e.target.value}))}
                                        placeholder="Describe the work performed (min. 10 characters)"
                                    />
                                    {formErrors.description && <p className="text-sm text-red-600 mt-1">{formErrors.description[0]}</p>}
                                </div>

                                <div>
                                    <label className="ti-form-label">Task type</label>
                                    <select
                                        className="ti-form-input"
                                        value={form.task_type}
                                        onChange={(e) => setForm((f) => ({...f, task_type: e.target.value}))}
                                    >
                                        {TASK_TYPES.map((t) => (
                                            <option key={t.value} value={t.value}>{t.label}</option>
                                        ))}
                                    </select>
                                </div>

                                <div className="flex items-center gap-2">
                                    <input
                                        id="billable"
                                        type="checkbox"
                                        checked={form.billable}
                                        onChange={(e) => setForm((f) => ({...f, billable: e.target.checked}))}
                                    />
                                    <label htmlFor="billable" className="ti-form-label mb-0">Billable</label>
                                </div>

                                <div>
                                    <label className="ti-form-label">Hourly rate (optional)</label>
                                    <input
                                        type="number"
                                        step="0.01"
                                        min="0"
                                        className="ti-form-input"
                                        value={form.hourly_rate}
                                        onChange={(e) => setForm((f) => ({
                                            ...f,
                                            hourly_rate: e.target.value === '' ? '' : Number(e.target.value),
                                        }))}
                                    />
                                </div>
                            </div>

                            <div className="flex items-center justify-end gap-2 px-5 py-4 border-t border-gray-200">
                                <button type="button" onClick={closeForm} className="px-4 py-2 text-sm border rounded-lg hover:bg-gray-50">
                                    Cancel
                                </button>
                                <button type="submit" disabled={submitting} className="ti-btn ti-btn-primary px-4 py-2">
                                    {submitting ? 'Saving…' : editingEntry ? 'Update' : 'Save draft'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* View modal */}
            {viewEntry && (
                <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-lg max-h-[90vh] 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">Time Entry #{viewEntry.id}</h3>
                            <button type="button" className="p-1.5 text-gray-400 hover:text-gray-600 rounded" onClick={() => setViewEntry(null)} aria-label="Close">
                                <i className="ri ri-close-line text-lg"></i>
                            </button>
                        </div>
                        <div className="px-5 py-5 space-y-3 text-sm">
                            <p><strong>Date:</strong> {viewEntry.entry_date ? new Date(viewEntry.entry_date).toLocaleDateString() : '—'}</p>
                            <p><strong>Matter:</strong> {viewEntry.matter?.reference_number ?? '—'} — {viewEntry.matter?.matter_type ?? ''}</p>
                            <p><strong>User:</strong> {viewEntry.user?.name ?? '—'}</p>
                            <p><strong>Duration:</strong> {formatDuration(viewEntry.duration_minutes ?? 0)}</p>
                            <p><strong>Status:</strong> <span className={statusClass(viewEntry.status)}>{statusLabel(viewEntry.status)}</span></p>
                            <p><strong>Billable:</strong> {viewEntry.billable ? 'Yes' : 'No'}</p>
                            {viewEntry.hourly_rate != null && <p><strong>Rate:</strong> {viewEntry.hourly_rate}</p>}
                            {viewEntry.task_type && <p><strong>Task:</strong> {statusLabel(viewEntry.task_type)}</p>}
                            {viewEntry.rejection_reason && (
                                <p><strong>Rejection reason:</strong> {viewEntry.rejection_reason}</p>
                            )}
                            <div>
                                <strong>Description</strong>
                                <p className="mt-1 text-gray-700 whitespace-pre-wrap">{viewEntry.description}</p>
                            </div>
                            {viewEntry.submitted_at && (
                                <p><strong>Submitted:</strong> {new Date(viewEntry.submitted_at).toLocaleString()}</p>
                            )}
                            {viewEntry.approved_at && (
                                <p><strong>Approved:</strong> {new Date(viewEntry.approved_at).toLocaleString()}</p>
                            )}
                        </div>
                        <div className="flex justify-end px-5 py-4 border-t border-gray-200">
                            <button type="button" onClick={() => setViewEntry(null)} className="px-4 py-2 text-sm border rounded-lg hover:bg-gray-50">
                                Close
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </MainLayout>
    );
}
