import { useState } from 'react';
import AppLayout from '@/Layouts/AppLayout';
import { DataTable } from '@/Components/ui/DataTable';
import { useAll } from '@/hooks/useResource';
import { PeriodeSelect } from '@/Components/ui/PeriodeSelect';
import { usePeriodeStore } from '@/store/usePeriodeStore';

interface Row {
    id: number;
    kode?: string;
    nama?: string;
    name?: string;
    status: string;
    kegiatans_count: number;
}

const TABS = [
    { key: 'pa', label: 'PA', path: '/rekap-sdm/pa' },
    { key: 'narasumber', label: 'Narasumber', path: '/rekap-sdm/narasumber' },
    { key: 'klien', label: 'Klien', path: '/rekap-sdm/klien' },
] as const;

export default function RekapSdmIndex() {
    const [tab, setTab] = useState<(typeof TABS)[number]['key']>('pa');
    const { bulan, tahun } = usePeriodeStore();
    const active = TABS.find((t) => t.key === tab)!;
    const { data, isLoading } = useAll<Row[]>(`rekap-sdm-${tab}`, active.path, { bulan, tahun });

    return (
        <AppLayout>
            <div className="flex flex-col gap-5">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 bg-white border border-slate-200/80 px-4 sm:px-6 py-4 sm:py-4.5 rounded-2xl shadow-sm">
                    <h1 className="text-lg sm:text-xl font-bold text-gray-900">Rekap SDM & Klien</h1>
                    <PeriodeSelect />
                </div>

                <div className="flex gap-1 border-b border-gray-200 overflow-x-auto">
                    {TABS.map((t) => (
                        <button
                            key={t.key}
                            onClick={() => setTab(t.key)}
                            className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px whitespace-nowrap ${
                                tab === t.key ? 'border-sky-600 text-sky-600' : 'border-transparent text-gray-500 hover:text-gray-700'
                            }`}
                        >
                            {t.label}
                        </button>
                    ))}
                </div>

                <DataTable
                    columns={[
                        ...(tab !== 'pa' ? [{ header: 'Kode', cell: (r: Row) => r.kode }] : []),
                        { header: 'Nama', cell: (r: Row) => r.name ?? r.nama },
                        { header: 'Status', cell: (r: Row) => r.status },
                        { header: 'Frekuensi Tugas', cell: (r: Row) => r.kegiatans_count },
                    ]}
                    rows={data ?? []}
                    rowKey={(r: Row) => r.id}
                    isLoading={isLoading}
                />
            </div>
        </AppLayout>
    );
}
