import React, {useEffect, useMemo, useRef, useState} from 'react';
import {usePage} from '@inertiajs/react';
import Modal from '@/components/ui/modal/Modal';
import {makeGetRequest, makePostRequest, makePutRequest} from '@/lib/request';
import {notify} from '@/lib/notify';

type UserOption = { id: number; name: string; email?: string | null };
type StaffOption = { id: number; name: string; email?: string | null; department?: string | null; job_title?: string | null };
type MatterOption = { id: number; reference_number: string; matter_type?: string | null; client?: { name?: string | null } | null };
type AttendanceSession = {
    id: number;
    user_id: number;
    clock_in_at: string;
    clock_out_at?: string | null;
    total_minutes: number;
    notes?: string | null;
    user?: UserOption | null;
    telemetry_points?: Array<{ id: number }>;
    telemetry_points_count?: number;
};
type StaffMetric = {
    user: UserOption;
    staff_profile?: { job_title?: string | null; department?: string | null } | null;
    billable_hours: number;
    non_billable_hours: number;
    tasks_assigned: number;
    tasks_completed: number;
    task_completion_rate?: number | null;
    overdue_tasks: number;
    attendance_days: number;
    attendance_rate?: number | null;
    average_session_hours: number;
    gps_points: number;
    punctuality_score?: number | null;
    leave_days: number;
    active_goals: number;
    completed_goals: number;
    average_review_rating?: number | null;
    performance_index?: number | null;
};
type PerformanceReview = {
    id: number;
    review_type: string;
    status: string;
    overall_rating?: number | null;
    review_period_start: string;
    review_period_end: string;
    next_review_date?: string | null;
    reviewee?: UserOption | null;
    reviewer?: UserOption | null;
    manager_feedback?: string | null;
    self_evaluation?: string | null;
};
type PerformanceGoal = {
    id: number;
    title: string;
    metric_type: string;
    target_value?: number | string | null;
    current_value?: number | string | null;
    unit?: string | null;
    status: string;
    due_date?: string | null;
    user?: UserOption | null;
    related_matter?: MatterOption | null;
};
type OverviewPayload = {
    summary: {
        staff_count: number;
        active_sessions: number;
        reviews_due: number;
        active_goals: number;
        telemetry_points_today: number;
    };
    staff_metrics: StaffMetric[];
    reviews: PerformanceReview[];
    goals: PerformanceGoal[];
    recent_attendance: AttendanceSession[];
};

function titleCase(value?: string | null): string {
    return String(value || '-').replace(/_/g, ' ').replace(/\b\w/g, char => char.toUpperCase());
}

function dateLabel(value?: string | null): string {
    return value ? new Date(value).toLocaleDateString() : '-';
}

function dateTimeLabel(value?: string | null): string {
    return value ? new Date(value).toLocaleString() : '-';
}

function durationLabel(totalMinutes?: number | null): string {
    const minutes = Number(totalMinutes || 0);
    const hours = Math.floor(minutes / 60);
    const remainder = minutes % 60;
    if (!hours) return `${remainder}m`;
    if (!remainder) return `${hours}h`;
    return `${hours}h ${remainder}m`;
}

async function getCurrentPositionData(): Promise<Record<string, any>> {
    if (!navigator.geolocation) return {};

    return new Promise(resolve => {
        navigator.geolocation.getCurrentPosition(
            position => resolve({
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
                accuracy: position.coords.accuracy,
                altitude: position.coords.altitude ?? null,
                speed: position.coords.speed ?? null,
                heading: position.coords.heading ?? null,
                source: 'gps',
                metadata: {captured_from: 'browser'},
            }),
            () => resolve({source: 'manual'}),
            {enableHighAccuracy: true, timeout: 10000, maximumAge: 0},
        );
    });
}

export default function PerformancePanel(): JSX.Element {
    const inertiaPage = usePage<{ auth: { user: { id: number; token?: string; api_token?: string } } }>();
    const authUser = inertiaPage.props.auth.user;
    const token = authUser?.token ?? authUser?.api_token;

    const [overview, setOverview] = useState<OverviewPayload | null>(null);
    const [currentSession, setCurrentSession] = useState<AttendanceSession | null>(null);
    const [loading, setLoading] = useState(false);
    const [clocking, setClocking] = useState(false);
    const [staffOptions, setStaffOptions] = useState<StaffOption[]>([]);
    const [matters, setMatters] = useState<MatterOption[]>([]);
    const [fromDate, setFromDate] = useState(new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().slice(0, 10));
    const [toDate, setToDate] = useState(new Date().toISOString().slice(0, 10));
    const [selectedUserId, setSelectedUserId] = useState('');
    const [geoState, setGeoState] = useState<'idle' | 'watching' | 'blocked'>('idle');

    const [showReviewModal, setShowReviewModal] = useState(false);
    const [showGoalModal, setShowGoalModal] = useState(false);
    const [goalToUpdate, setGoalToUpdate] = useState<PerformanceGoal | null>(null);

    const [reviewForm, setReviewForm] = useState({
        reviewee_user_id: '',
        reviewer_user_id: String(authUser?.id ?? ''),
        review_period_start: fromDate,
        review_period_end: toDate,
        review_type: 'quarterly',
        overall_rating: '',
        status: 'draft',
        manager_feedback: '',
        self_evaluation: '',
        next_review_date: '',
    });
    const [goalForm, setGoalForm] = useState({
        user_id: '',
        related_matter_id: '',
        title: '',
        description: '',
        metric_type: 'billable_hours',
        target_value: '',
        current_value: '0',
        unit: 'hours',
        due_date: '',
        status: 'active',
    });
    const [goalUpdateForm, setGoalUpdateForm] = useState({
        current_value: '0',
        status: 'active',
    });
    const [savingReview, setSavingReview] = useState(false);
    const [savingGoal, setSavingGoal] = useState(false);
    const [updatingGoal, setUpdatingGoal] = useState(false);

    const watchIdRef = useRef<number | null>(null);
    const lastSessionIdRef = useRef<number | null>(null);

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

    useEffect(() => {
        fetchOverview();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [fromDate, toDate, selectedUserId]);

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

    useEffect(() => {
        setReviewForm(current => ({
            ...current,
            review_period_start: fromDate,
            review_period_end: toDate,
        }));
    }, [fromDate, toDate]);

    useEffect(() => {
        if (!goalToUpdate) return;
        setGoalUpdateForm({
            current_value: String(goalToUpdate.current_value ?? 0),
            status: goalToUpdate.status,
        });
    }, [goalToUpdate]);

    useEffect(() => {
        if (!currentSession || currentSession.clock_out_at || !navigator.geolocation) {
            if (watchIdRef.current !== null) navigator.geolocation.clearWatch(watchIdRef.current);
            watchIdRef.current = null;
            setGeoState('idle');
            return;
        }

        if (lastSessionIdRef.current === currentSession.id && watchIdRef.current !== null) return;

        lastSessionIdRef.current = currentSession.id;
        setGeoState('watching');
        watchIdRef.current = navigator.geolocation.watchPosition(
            async position => {
                try {
                    await makePostRequest(`/api/hr/attendance/${currentSession.id}/telemetry`, {
                        captured_at: new Date().toISOString(),
                        latitude: position.coords.latitude,
                        longitude: position.coords.longitude,
                        accuracy: position.coords.accuracy,
                        altitude: position.coords.altitude ?? null,
                        speed: position.coords.speed ?? null,
                        heading: position.coords.heading ?? null,
                        source: 'gps',
                        metadata: {captured_from: 'watchPosition'},
                    }, {token});
                } catch {
                    //
                }
            },
            () => {
                setGeoState('blocked');
            },
            {enableHighAccuracy: true, maximumAge: 60000, timeout: 15000},
        );

        return () => {
            if (watchIdRef.current !== null) navigator.geolocation.clearWatch(watchIdRef.current);
            watchIdRef.current = null;
        };
    }, [currentSession, token]);

    const currentMetric = useMemo(() => {
        return overview?.staff_metrics.find(item => item.user.id === authUser.id) ?? null;
    }, [overview, authUser.id]);

    async function fetchReferences() {
        try {
            const [staffRes, matterRes] = await Promise.all([
                makeGetRequest('/api/hr/staff?per_page=200', {token}),
                makeGetRequest('/api/matters?per_page=200', {token}),
            ]);
            const staffPayload = staffRes.data?.result ?? staffRes.data ?? {};
            const mattersPayload = matterRes.data?.result ?? matterRes.data ?? {};
            const profiles = Array.isArray(staffPayload?.data ?? staffPayload) ? (staffPayload.data ?? staffPayload) : [];
            setStaffOptions(profiles.map((profile: any) => ({
                id: profile.user_id,
                name: profile.user?.name || 'Unknown staff',
                email: profile.user?.email || null,
                department: profile.department || null,
                job_title: profile.job_title || null,
            })));
            setMatters(Array.isArray(mattersPayload?.data ?? mattersPayload) ? (mattersPayload.data ?? mattersPayload) : []);
        } catch {
            //
        }
    }

    async function fetchOverview() {
        setLoading(true);
        try {
            const params = new URLSearchParams({from: fromDate, to: toDate});
            if (selectedUserId) params.append('user_id', selectedUserId);
            const res = await makeGetRequest(`/api/hr/performance/overview?${params.toString()}`, {token});
            setOverview(res.data?.result ?? null);
        } catch (error: any) {
            notify.toastErrorMessage(error?.response?.data?.message || 'Failed to load performance dashboard');
        } finally {
            setLoading(false);
        }
    }

    async function fetchCurrentSession() {
        try {
            const res = await makeGetRequest('/api/hr/attendance/current', {token});
            setCurrentSession(res.data?.result ?? null);
        } catch {
            //
        }
    }

    async function handleClockIn() {
        setClocking(true);
        try {
            const coords = await getCurrentPositionData();
            const res = await makePostRequest('/api/hr/attendance/clock-in', {
                ...coords,
                clock_in_at: new Date().toISOString(),
                source: coords.source ?? 'web',
            }, {token});
            setCurrentSession(res.data?.result ?? null);
            notify.toastSuccessMessage('Clocked in');
            fetchOverview();
        } catch (error: any) {
            notify.toastErrorMessage(error?.response?.data?.message || 'Failed to clock in');
        } finally {
            setClocking(false);
        }
    }

    async function handleClockOut() {
        if (!currentSession) return;
        setClocking(true);
        try {
            const coords = await getCurrentPositionData();
            await makePostRequest(`/api/hr/attendance/${currentSession.id}/clock-out`, {
                ...coords,
                clock_out_at: new Date().toISOString(),
                source: coords.source ?? 'web',
            }, {token});
            setCurrentSession(null);
            notify.toastSuccessMessage('Clocked out');
            fetchOverview();
        } catch (error: any) {
            notify.toastErrorMessage(error?.response?.data?.message || 'Failed to clock out');
        } finally {
            setClocking(false);
        }
    }

    async function submitReview(e: React.FormEvent) {
        e.preventDefault();
        setSavingReview(true);
        try {
            await makePostRequest('/api/hr/performance/reviews', {
                reviewee_user_id: Number(reviewForm.reviewee_user_id),
                reviewer_user_id: reviewForm.reviewer_user_id ? Number(reviewForm.reviewer_user_id) : null,
                review_period_start: reviewForm.review_period_start,
                review_period_end: reviewForm.review_period_end,
                review_type: reviewForm.review_type,
                overall_rating: reviewForm.overall_rating ? Number(reviewForm.overall_rating) : null,
                status: reviewForm.status,
                manager_feedback: reviewForm.manager_feedback || null,
                self_evaluation: reviewForm.self_evaluation || null,
                next_review_date: reviewForm.next_review_date || null,
            }, {token});
            notify.toastSuccessMessage('Performance review saved');
            setReviewForm(current => ({
                ...current,
                reviewee_user_id: '',
                overall_rating: '',
                manager_feedback: '',
                self_evaluation: '',
                next_review_date: '',
                status: 'draft',
            }));
            setShowReviewModal(false);
            fetchOverview();
        } catch (error: any) {
            notify.toastErrorMessage(error?.response?.data?.message || 'Failed to save review');
        } finally {
            setSavingReview(false);
        }
    }

    async function submitGoal(e: React.FormEvent) {
        e.preventDefault();
        setSavingGoal(true);
        try {
            await makePostRequest('/api/hr/performance/goals', {
                user_id: Number(goalForm.user_id),
                related_matter_id: goalForm.related_matter_id ? Number(goalForm.related_matter_id) : null,
                title: goalForm.title,
                description: goalForm.description || null,
                metric_type: goalForm.metric_type,
                target_value: goalForm.target_value ? Number(goalForm.target_value) : null,
                current_value: goalForm.current_value ? Number(goalForm.current_value) : 0,
                unit: goalForm.unit || null,
                due_date: goalForm.due_date || null,
                status: goalForm.status,
            }, {token});
            notify.toastSuccessMessage('Performance goal saved');
            setGoalForm(current => ({
                ...current,
                user_id: '',
                related_matter_id: '',
                title: '',
                description: '',
                target_value: '',
                current_value: '0',
                due_date: '',
                status: 'active',
            }));
            setShowGoalModal(false);
            fetchOverview();
        } catch (error: any) {
            notify.toastErrorMessage(error?.response?.data?.message || 'Failed to save goal');
        } finally {
            setSavingGoal(false);
        }
    }

    async function submitGoalUpdate(e: React.FormEvent) {
        e.preventDefault();
        if (!goalToUpdate) return;

        setUpdatingGoal(true);
        try {
            await makePutRequest(`/api/hr/performance/goals/${goalToUpdate.id}`, {
                current_value: Number(goalUpdateForm.current_value),
                status: goalUpdateForm.status,
            }, {token});
            notify.toastSuccessMessage('Goal updated');
            setGoalToUpdate(null);
            fetchOverview();
        } catch (error: any) {
            notify.toastErrorMessage(error?.response?.data?.message || 'Failed to update goal');
        } finally {
            setUpdatingGoal(false);
        }
    }

    return (
        <div className="space-y-4">
            <div className="grid grid-cols-12 gap-4">
                <MetricCard title="Active Sessions" value={String(overview?.summary.active_sessions ?? 0)} tone="primary" />
                <MetricCard title="Reviews Due" value={String(overview?.summary.reviews_due ?? 0)} tone="warning" />
                <MetricCard title="Active Goals" value={String(overview?.summary.active_goals ?? 0)} tone="success" />
                <MetricCard title="Telemetry Today" value={String(overview?.summary.telemetry_points_today ?? 0)} tone="danger" />
            </div>

            <div className="grid grid-cols-12 gap-4">
                <div className="col-span-12 xl:col-span-4">
                    <div className="box">
                        <div className="box-header"><h5 className="box-title">Attendance</h5></div>
                        <div className="box-body space-y-4">
                            <div className="rounded border border-defaultborder dark:border-defaultborder/10 p-4">
                                <div className="text-sm text-gray-500 mb-1">Current session</div>
                                <div className="font-semibold">{currentSession ? `Clocked in ${dateTimeLabel(currentSession.clock_in_at)}` : 'Not clocked in'}</div>
                                <div className="text-xs text-gray-500 mt-1">
                                    GPS telemetry: {geoState === 'watching' ? 'active' : geoState === 'blocked' ? 'blocked by browser/device' : 'idle'}
                                </div>
                                <div className="text-xs text-gray-500 mt-1">
                                    Logged telemetry points: {currentSession?.telemetry_points?.length ?? currentSession?.telemetry_points_count ?? 0}
                                </div>
                                <div className="mt-4 flex flex-wrap gap-2">
                                    {!currentSession ? (
                                        <button type="button" className="ti-btn ti-btn-primary py-2 px-4" disabled={clocking} onClick={handleClockIn}>
                                            {clocking ? 'Clocking In...' : 'Clock In'}
                                        </button>
                                    ) : (
                                        <button type="button" className="ti-btn ti-btn-danger py-2 px-4" disabled={clocking} onClick={handleClockOut}>
                                            {clocking ? 'Clocking Out...' : 'Clock Out'}
                                        </button>
                                    )}
                                </div>
                            </div>

                            <div className="rounded border border-defaultborder dark:border-defaultborder/10 p-4">
                                <div className="text-sm text-gray-500 mb-2">My current period metrics</div>
                                <div className="grid grid-cols-2 gap-3 text-sm">
                                    <div><span className="text-gray-500">Billable</span><div className="font-medium">{currentMetric?.billable_hours ?? 0}h</div></div>
                                    <div><span className="text-gray-500">Attendance</span><div className="font-medium">{currentMetric?.attendance_days ?? 0} day(s)</div></div>
                                    <div><span className="text-gray-500">Completion</span><div className="font-medium">{currentMetric?.task_completion_rate ?? 0}%</div></div>
                                    <div><span className="text-gray-500">Performance</span><div className="font-medium">{currentMetric?.performance_index ?? '-'}</div></div>
                                </div>
                            </div>

                            <div className="grid grid-cols-1 gap-3 md:grid-cols-3">
                                <div>
                                    <label className="ti-form-label">From</label>
                                    <input type="date" className="ti-form-input" value={fromDate} onChange={e => setFromDate(e.target.value)} />
                                </div>
                                <div>
                                    <label className="ti-form-label">To</label>
                                    <input type="date" className="ti-form-input" value={toDate} onChange={e => setToDate(e.target.value)} />
                                </div>
                                <div>
                                    <label className="ti-form-label">Staff filter</label>
                                    <select className="ti-form-input" value={selectedUserId} onChange={e => setSelectedUserId(e.target.value)}>
                                        <option value="">All staff</option>
                                        {staffOptions.map(user => <option key={user.id} value={user.id}>{user.name}</option>)}
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div className="col-span-12 xl:col-span-8">
                    <div className="box">
                        <div className="box-header"><h5 className="box-title">Performance Metrics</h5></div>
                        <div className="box-body overflow-x-auto">
                            <table className="table whitespace-nowrap min-w-full">
                                <thead>
                                <tr>
                                    <th>Staff</th>
                                    <th>Billable</th>
                                    <th>Tasks</th>
                                    <th>Attendance</th>
                                    <th>GPS</th>
                                    <th>Goals</th>
                                    <th>Reviews</th>
                                    <th>Index</th>
                                </tr>
                                </thead>
                                <tbody>
                                {overview?.staff_metrics.map(metric => (
                                    <tr key={metric.user.id}>
                                        <td>
                                            <div className="font-medium">{metric.user.name}</div>
                                            <div className="text-xs text-gray-500">{metric.staff_profile?.job_title || '-'} · {metric.staff_profile?.department || '-'}</div>
                                        </td>
                                        <td>
                                            <div>{metric.billable_hours}h</div>
                                            <div className="text-xs text-gray-500">{metric.non_billable_hours}h non-billable</div>
                                        </td>
                                        <td>
                                            <div>{metric.tasks_completed}/{metric.tasks_assigned}</div>
                                            <div className="text-xs text-gray-500">{metric.task_completion_rate ?? 0}% complete · {metric.overdue_tasks} overdue</div>
                                        </td>
                                        <td>
                                            <div>{metric.attendance_days} day(s)</div>
                                            <div className="text-xs text-gray-500">{metric.average_session_hours}h avg · {metric.punctuality_score ?? 0}% punctual</div>
                                        </td>
                                        <td>{metric.gps_points}</td>
                                        <td>{metric.active_goals} active / {metric.completed_goals} done</td>
                                        <td>{metric.average_review_rating ?? '-'}</td>
                                        <td><span className={`font-semibold ${Number(metric.performance_index ?? 0) >= 80 ? 'text-success' : Number(metric.performance_index ?? 0) >= 60 ? 'text-warning' : 'text-danger'}`}>{metric.performance_index ?? '-'}</span></td>
                                    </tr>
                                ))}
                                {!overview?.staff_metrics.length ? (
                                    <tr><td colSpan={8} className="text-center py-6 text-gray-500">{loading ? 'Loading metrics...' : 'No performance metrics found'}</td></tr>
                                ) : null}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div className="grid grid-cols-12 gap-4">
                <div className="col-span-12 xl:col-span-3">
                    <div className="box h-full">
                        <div className="box-header"><h5 className="box-title">Reviews</h5></div>
                        <div className="box-body space-y-4">
                            <p className="text-sm text-gray-500">Create and record formal performance reviews for staff in the current reporting period.</p>
                            <button type="button" className="ti-btn ti-btn-primary py-2 px-4" onClick={() => setShowReviewModal(true)}>New Review</button>
                        </div>
                    </div>
                </div>

                <div className="col-span-12 xl:col-span-3">
                    <div className="box h-full">
                        <div className="box-header"><h5 className="box-title">Goals</h5></div>
                        <div className="box-body space-y-4">
                            <p className="text-sm text-gray-500">Assign measurable goals, link them to matters if needed, and track progress over time.</p>
                            <button type="button" className="ti-btn ti-btn-primary py-2 px-4" onClick={() => setShowGoalModal(true)}>New Goal</button>
                        </div>
                    </div>
                </div>

                <div className="col-span-12 xl:col-span-6">
                    <div className="box">
                        <div className="box-header"><h5 className="box-title">Recent Reviews & Goals</h5></div>
                        <div className="box-body space-y-4">
                            <div>
                                <div className="font-medium mb-2">Reviews</div>
                                <div className="space-y-3 max-h-[260px] overflow-auto">
                                    {overview?.reviews.map(review => (
                                        <div key={review.id} className="rounded border border-defaultborder dark:border-defaultborder/10 p-3">
                                            <div className="flex items-center justify-between gap-3">
                                                <div className="font-medium">{review.reviewee?.name || '-'}</div>
                                                <span className={`badge ${review.status === 'completed' ? 'bg-success/10 text-success' : review.status === 'submitted' ? 'bg-primary/10 text-primary' : 'bg-warning/10 text-warning'}`}>{titleCase(review.status)}</span>
                                            </div>
                                            <div className="text-xs text-gray-500 mt-1">{titleCase(review.review_type)} · {dateLabel(review.review_period_start)} - {dateLabel(review.review_period_end)}</div>
                                            <div className="text-sm mt-2">Rating: {review.overall_rating ?? '-'}</div>
                                        </div>
                                    ))}
                                    {!overview?.reviews.length ? <div className="text-sm text-gray-500">No reviews yet.</div> : null}
                                </div>
                            </div>
                            <div>
                                <div className="font-medium mb-2">Goals</div>
                                <div className="space-y-3 max-h-[260px] overflow-auto">
                                    {overview?.goals.map(goal => (
                                        <div key={goal.id} className="rounded border border-defaultborder dark:border-defaultborder/10 p-3">
                                            <div className="flex items-center justify-between gap-3">
                                                <div className="font-medium">{goal.title}</div>
                                                <button type="button" className="text-sm text-primary" onClick={() => setGoalToUpdate(goal)}>Update</button>
                                            </div>
                                            <div className="text-xs text-gray-500 mt-1">{goal.user?.name || '-'} · {titleCase(goal.metric_type)} · due {dateLabel(goal.due_date)}</div>
                                            <div className="text-sm mt-2">{goal.current_value ?? 0}/{goal.target_value ?? '-'} {goal.unit || ''}</div>
                                        </div>
                                    ))}
                                    {!overview?.goals.length ? <div className="text-sm text-gray-500">No goals yet.</div> : null}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div className="box">
                <div className="box-header"><h5 className="box-title">Recent Attendance Sessions</h5></div>
                <div className="box-body overflow-x-auto">
                    <table className="table whitespace-nowrap min-w-full">
                        <thead>
                        <tr>
                            <th>Staff</th>
                            <th>Clock In</th>
                            <th>Clock Out</th>
                            <th>Worked</th>
                            <th>Telemetry</th>
                            <th>Notes</th>
                        </tr>
                        </thead>
                        <tbody>
                        {overview?.recent_attendance.map(session => (
                            <tr key={session.id}>
                                <td>{session.user?.name || '-'}</td>
                                <td>{dateTimeLabel(session.clock_in_at)}</td>
                                <td>{dateTimeLabel(session.clock_out_at)}</td>
                                <td>{durationLabel(session.total_minutes)}</td>
                                <td>{session.telemetry_points?.length ?? session.telemetry_points_count ?? 0}</td>
                                <td>{session.notes || '-'}</td>
                            </tr>
                        ))}
                        {!overview?.recent_attendance.length ? (
                            <tr><td colSpan={6} className="text-center py-6 text-gray-500">{loading ? 'Loading attendance...' : 'No attendance sessions found'}</td></tr>
                        ) : null}
                        </tbody>
                    </table>
                </div>
            </div>

            {showReviewModal ? (
                <Modal
                    open={true}
                    title="New Review"
                    onClose={() => setShowReviewModal(false)}
                    footer={(
                        <>
                            <button type="button" className="ti-btn ti-btn-light py-2 px-4" onClick={() => setShowReviewModal(false)}>Cancel</button>
                            <button type="submit" form="performance-review-form" disabled={savingReview || !reviewForm.reviewee_user_id} className="ti-btn ti-btn-primary py-2 px-4 disabled:opacity-40">{savingReview ? 'Saving...' : 'Save Review'}</button>
                        </>
                    )}
                >
                    <form id="performance-review-form" onSubmit={submitReview} className="space-y-4">
                        <div>
                            <label className="ti-form-label">Reviewee</label>
                            <select className="ti-form-input" value={reviewForm.reviewee_user_id} onChange={e => setReviewForm(current => ({...current, reviewee_user_id: e.target.value}))}>
                                <option value="">Select staff member</option>
                                {staffOptions.map(user => <option key={user.id} value={user.id}>{user.name}</option>)}
                            </select>
                        </div>
                        <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                            <div>
                                <label className="ti-form-label">Period start</label>
                                <input type="date" className="ti-form-input" value={reviewForm.review_period_start} onChange={e => setReviewForm(current => ({...current, review_period_start: e.target.value}))} />
                            </div>
                            <div>
                                <label className="ti-form-label">Period end</label>
                                <input type="date" className="ti-form-input" value={reviewForm.review_period_end} onChange={e => setReviewForm(current => ({...current, review_period_end: e.target.value}))} />
                            </div>
                        </div>
                        <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                            <select className="ti-form-input" value={reviewForm.review_type} onChange={e => setReviewForm(current => ({...current, review_type: e.target.value}))}>
                                <option value="quarterly">Quarterly</option>
                                <option value="semi_annual">Semi-annual</option>
                                <option value="annual">Annual</option>
                                <option value="custom">Custom</option>
                            </select>
                            <input type="number" min="0" max="5" step="0.1" className="ti-form-input" placeholder="Overall rating" value={reviewForm.overall_rating} onChange={e => setReviewForm(current => ({...current, overall_rating: e.target.value}))} />
                        </div>
                        <textarea className="ti-form-input" rows={3} placeholder="Manager feedback" value={reviewForm.manager_feedback} onChange={e => setReviewForm(current => ({...current, manager_feedback: e.target.value}))} />
                        <textarea className="ti-form-input" rows={3} placeholder="Self evaluation" value={reviewForm.self_evaluation} onChange={e => setReviewForm(current => ({...current, self_evaluation: e.target.value}))} />
                        <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                            <select className="ti-form-input" value={reviewForm.status} onChange={e => setReviewForm(current => ({...current, status: e.target.value}))}>
                                <option value="draft">Draft</option>
                                <option value="submitted">Submitted</option>
                                <option value="completed">Completed</option>
                            </select>
                            <input type="date" className="ti-form-input" value={reviewForm.next_review_date} onChange={e => setReviewForm(current => ({...current, next_review_date: e.target.value}))} />
                        </div>
                    </form>
                </Modal>
            ) : null}

            {showGoalModal ? (
                <Modal
                    open={true}
                    title="New Goal"
                    onClose={() => setShowGoalModal(false)}
                    footer={(
                        <>
                            <button type="button" className="ti-btn ti-btn-light py-2 px-4" onClick={() => setShowGoalModal(false)}>Cancel</button>
                            <button type="submit" form="performance-goal-form" disabled={savingGoal || !goalForm.user_id || !goalForm.title.trim()} className="ti-btn ti-btn-primary py-2 px-4 disabled:opacity-40">{savingGoal ? 'Saving...' : 'Save Goal'}</button>
                        </>
                    )}
                >
                    <form id="performance-goal-form" onSubmit={submitGoal} className="space-y-4">
                        <div>
                            <label className="ti-form-label">Staff member</label>
                            <select className="ti-form-input" value={goalForm.user_id} onChange={e => setGoalForm(current => ({...current, user_id: e.target.value}))}>
                                <option value="">Select staff member</option>
                                {staffOptions.map(user => <option key={user.id} value={user.id}>{user.name}</option>)}
                            </select>
                        </div>
                        <input className="ti-form-input" placeholder="Goal title" value={goalForm.title} onChange={e => setGoalForm(current => ({...current, title: e.target.value}))} />
                        <textarea className="ti-form-input" rows={3} placeholder="Description" value={goalForm.description} onChange={e => setGoalForm(current => ({...current, description: e.target.value}))} />
                        <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                            <select className="ti-form-input" value={goalForm.metric_type} onChange={e => setGoalForm(current => ({...current, metric_type: e.target.value}))}>
                                <option value="billable_hours">Billable hours</option>
                                <option value="task_completion">Task completion</option>
                                <option value="attendance">Attendance</option>
                                <option value="matter_outcome">Matter outcome</option>
                                <option value="custom">Custom</option>
                            </select>
                            <input className="ti-form-input" placeholder="Unit" value={goalForm.unit} onChange={e => setGoalForm(current => ({...current, unit: e.target.value}))} />
                        </div>
                        <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                            <input type="number" min="0" step="0.01" className="ti-form-input" placeholder="Target value" value={goalForm.target_value} onChange={e => setGoalForm(current => ({...current, target_value: e.target.value}))} />
                            <input type="number" min="0" step="0.01" className="ti-form-input" placeholder="Current value" value={goalForm.current_value} onChange={e => setGoalForm(current => ({...current, current_value: e.target.value}))} />
                        </div>
                        <div>
                            <label className="ti-form-label">Linked matter</label>
                            <select className="ti-form-input" value={goalForm.related_matter_id} onChange={e => setGoalForm(current => ({...current, related_matter_id: e.target.value}))}>
                                <option value="">No linked matter</option>
                                {matters.map(matter => <option key={matter.id} value={matter.id}>{matter.reference_number}</option>)}
                            </select>
                        </div>
                        <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                            <input type="date" className="ti-form-input" value={goalForm.due_date} onChange={e => setGoalForm(current => ({...current, due_date: e.target.value}))} />
                            <select className="ti-form-input" value={goalForm.status} onChange={e => setGoalForm(current => ({...current, status: e.target.value}))}>
                                <option value="active">Active</option>
                                <option value="completed">Completed</option>
                                <option value="on_hold">On hold</option>
                                <option value="cancelled">Cancelled</option>
                            </select>
                        </div>
                    </form>
                </Modal>
            ) : null}

            {goalToUpdate ? (
                <Modal
                    open={true}
                    title={`Update Goal: ${goalToUpdate.title}`}
                    onClose={() => setGoalToUpdate(null)}
                    footer={(
                        <>
                            <button type="button" className="ti-btn ti-btn-light py-2 px-4" onClick={() => setGoalToUpdate(null)}>Cancel</button>
                            <button type="submit" form="performance-goal-update-form" disabled={updatingGoal} className="ti-btn ti-btn-primary py-2 px-4 disabled:opacity-40">{updatingGoal ? 'Updating...' : 'Update Goal'}</button>
                        </>
                    )}
                >
                    <form id="performance-goal-update-form" onSubmit={submitGoalUpdate} className="space-y-4">
                        <div className="text-sm text-gray-500">
                            {goalToUpdate.user?.name || '-'} · {titleCase(goalToUpdate.metric_type)} · due {dateLabel(goalToUpdate.due_date)}
                        </div>
                        <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                            <input type="number" min="0" step="0.01" className="ti-form-input" placeholder="Current progress value" value={goalUpdateForm.current_value} onChange={e => setGoalUpdateForm(current => ({...current, current_value: e.target.value}))} />
                            <select className="ti-form-input" value={goalUpdateForm.status} onChange={e => setGoalUpdateForm(current => ({...current, status: e.target.value}))}>
                                <option value="active">Active</option>
                                <option value="completed">Completed</option>
                                <option value="on_hold">On hold</option>
                                <option value="cancelled">Cancelled</option>
                            </select>
                        </div>
                        <div className="text-sm text-gray-500">Target: {goalToUpdate.target_value ?? '-'} {goalToUpdate.unit || ''}</div>
                    </form>
                </Modal>
            ) : null}
        </div>
    );
}

function MetricCard({title, value, tone}: { title: string; value: string; tone: 'primary' | 'success' | 'warning' | 'danger' }): JSX.Element {
    const toneClass = {primary: 'text-primary', success: 'text-success', warning: 'text-warning', danger: 'text-danger'}[tone];
    return <div className="col-span-12 sm:col-span-6 xl:col-span-3"><div className="box"><div className="box-body"><p className="text-sm text-gray-500 mb-2">{title}</p><p className={`text-2xl font-semibold ${toneClass}`}>{value}</p></div></div></div>;
}
