import { Link, router, usePage, Head } from '@inertiajs/react';
import { useState, useEffect } from 'react';
import { Search, Users, RefreshCw, User, Calendar, MapPin } from 'lucide-react';
import AuthenticatedLayout from '@/layouts/AuthenticatedLayout';
import { formatDate } from '@/lib/utils';
import type { PageProps } from '@/types';

interface Teacher {
    id: number;
    api_teacher_id: number;
    nip: string | null;
    nik: string | null;
    nuptk: string | null;
    full_name: string;
    gender: 'L' | 'P' | null;
    birth_place: string | null;
    birth_date: string | null;
    phone: string | null;
    address: string | null;
    position: string | null;
    display_position: string | null;
    type: string | null;
    status: string | null;
    image_url: string | null;
    last_synced_at: string | null;
}

interface Props extends PageProps {
    teachers: {
        data: Teacher[];
        links: Array<{ url: string | null; label: string; active: boolean }>;
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    filters: {
        search?: string;
    };
}

export default function TeacherIndex() {
    const { teachers, filters } = usePage<Props>().props;
    const [searchVal, setSearchVal] = useState(filters.search || '');

    useEffect(() => {
        setSearchVal(filters.search || '');
    }, [filters]);

    function performSearch(params: { search?: string }) {
        router.get('/teachers', params, {
            preserveState: true,
            replace: true,
        });
    }

    function handleSearchSubmit(e: React.FormEvent) {
        e.preventDefault();
        performSearch({ search: searchVal });
    }

    function handleReset() {
        setSearchVal('');
        router.get('/teachers', {}, { replace: true });
    }

    return (
        <>
            <Head title="Data Guru" />
            <div className="space-y-6">
                {/* Header */}
                <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
                    <div>
                        <p className="text-sm text-text-muted">
                            Total terdaftar: {teachers.total} guru (lokal)
                        </p>
                    </div>
                    <Link
                        href="/sync"
                        className="inline-flex items-center justify-center gap-2 rounded-xl bg-primary-500/10 px-4 py-2 text-sm font-semibold text-primary-300 hover:bg-primary-500/20 transition-colors"
                    >
                        <RefreshCw className="h-4 w-4" />
                        Sync Data
                    </Link>
                </div>

                {/* Filters */}
                <div className="glass rounded-2xl p-5">
                    <form onSubmit={handleSearchSubmit} className="flex flex-col gap-4 sm:flex-row sm:items-center">
                        <div className="relative grow">
                            <Search className="absolute top-1/2 left-4 h-4 w-4 -translate-y-1/2 text-text-muted" />
                            <input
                                type="text"
                                placeholder="Cari Nama, NIP, atau NUPTK..."
                                className="w-full rounded-xl border border-border bg-surface pl-11 pr-4 py-2.5 text-sm placeholder:text-text-muted focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
                                value={searchVal}
                                onChange={(e) => setSearchVal(e.target.value)}
                            />
                        </div>

                        <div className="flex gap-2">
                            <button
                                type="submit"
                                className="flex-1 sm:flex-initial rounded-xl bg-primary-500 px-5 py-2.5 text-sm font-semibold text-white hover:bg-primary-400 transition-all glow-primary"
                            >
                                Cari
                            </button>
                            {filters.search && (
                                <button
                                    type="button"
                                    onClick={handleReset}
                                    className="rounded-xl bg-surface hover:bg-surface-hover px-4 py-2.5 text-sm font-semibold text-text transition-colors"
                                >
                                    Reset
                                </button>
                            )}
                        </div>
                    </form>
                </div>

                {/* Teachers Table */}
                <div className="glass overflow-hidden rounded-2xl">
                    <div className="overflow-x-auto">
                        <table className="w-full border-collapse text-left text-sm text-text">
                            <thead>
                                <tr className="border-b border-border bg-surface/50 text-xs font-semibold uppercase tracking-wider text-text-muted">
                                    <th className="w-12 px-6 py-4 text-center">No.</th>
                                    <th className="px-6 py-4">Nama Lengkap</th>
                                    <th className="px-6 py-4">NIP / NUPTK</th>
                                    <th className="px-6 py-4">Jabatan</th>
                                    <th className="px-6 py-4">JK</th>
                                    <th className="px-6 py-4">TTL</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-border/40">
                                {teachers.data.length > 0 ? (
                                    teachers.data.map((teacher, index) => (
                                        <tr key={teacher.id} className="hover:bg-surface-hover/30 transition-colors">
                                            <td className="px-6 py-4 text-center text-text-muted font-mono text-xs">
                                                {(teachers.current_page - 1) * teachers.per_page + index + 1}
                                            </td>
                                            <td className="px-6 py-4">
                                                <div className="flex items-center gap-3">
                                                    <div className="flex h-9 w-9 items-center justify-center rounded-full bg-primary-500/10 text-primary-400 overflow-hidden shrink-0">
                                                        {teacher.image_url ? (
                                                            <img src={teacher.image_url} alt={teacher.full_name} className="h-full w-full object-cover" />
                                                        ) : (
                                                            <User className="h-4.5 w-4.5" />
                                                        )}
                                                    </div>
                                                    <span className="font-semibold text-text-light">
                                                        {teacher.full_name}
                                                    </span>
                                                </div>
                                            </td>
                                            <td className="px-6 py-4">
                                                <div>
                                                    <p className="font-mono text-xs">
                                                        NIP: {teacher.nip ?? '-'}
                                                    </p>
                                                    <p className="text-xs text-text-muted">
                                                        NUPTK: {teacher.nuptk ?? '-'}
                                                    </p>
                                                </div>
                                            </td>
                                            <td className="px-6 py-4">
                                                <span className="inline-flex items-center rounded-md bg-emerald-500/10 px-2.5 py-0.5 text-xs font-medium text-emerald-400 ring-1 ring-inset ring-emerald-500/20">
                                                    {teacher.display_position || teacher.position || '-'}
                                                </span>
                                            </td>
                                            <td className="px-6 py-4 text-xs font-semibold">
                                                {teacher.gender === 'L' ? (
                                                    <span className="text-sky-400">
                                                        Laki-laki
                                                    </span>
                                                ) : teacher.gender === 'P' ? (
                                                    <span className="text-rose-400">
                                                        Perempuan
                                                    </span>
                                                ) : (
                                                    '-'
                                                )}
                                            </td>
                                            <td className="px-6 py-4">
                                                <div className="space-y-0.5 text-xs text-text-muted">
                                                    {teacher.birth_place && (
                                                        <div className="flex items-center gap-1">
                                                            <MapPin className="h-3 w-3" />
                                                            <span>
                                                                {teacher.birth_place}
                                                            </span>
                                                        </div>
                                                    )}
                                                    {teacher.birth_date && (
                                                        <div className="flex items-center gap-1">
                                                            <Calendar className="h-3 w-3" />
                                                            <span>
                                                                {formatDate(
                                                                    teacher.birth_date,
                                                                )}
                                                            </span>
                                                        </div>
                                                    )}
                                                    {!teacher.birth_place &&
                                                        !teacher.birth_date &&
                                                        '-'}
                                                </div>
                                            </td>
                                        </tr>
                                    ))
                                ) : (
                                    <tr>
                                        <td colSpan={6} className="px-6 py-12 text-center text-text-muted">
                                            <div className="flex flex-col items-center">
                                                <Users className="h-10 w-10 opacity-30 mb-3" />
                                                <p className="font-medium text-base">
                                                    Tidak ada guru ditemukan
                                                </p>
                                                <p className="text-xs mt-1">
                                                    Coba sesuaikan kata kunci pencarian.
                                                </p>
                                            </div>
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>

                {/* Pagination */}
                {teachers.last_page > 1 && (
                    <div className="flex justify-center gap-2">
                        {teachers.links.map((link, i) => (
                            <Link
                                key={i}
                                href={link.url || '#'}
                                className={`px-4 py-2 rounded-xl text-sm transition-colors ${
                                    link.active
                                        ? 'bg-primary-500 text-white font-bold'
                                        : 'bg-surface hover:bg-surface-hover text-text'
                                } ${!link.url ? 'opacity-50 cursor-not-allowed' : ''}`}
                                dangerouslySetInnerHTML={{ __html: link.label }}
                            />
                        ))}
                    </div>
                )}
            </div>
        </>
    );
}

TeacherIndex.layout = (page: any) => <AuthenticatedLayout title="Data Guru">{page}</AuthenticatedLayout>;
