'use client';

import { useState, useTransition } from 'react';
import { toast } from 'sonner';
import { createAwardeePH, deleteAwardeePH } from '@/lib/admin-actions';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Trash2, Plus, Trophy, Star, ChevronDown, ChevronRight } from 'lucide-react';
import { useRouter } from 'next/navigation';

type AwardeeWithPengurus = {
    id: string;
    periode: string;
    tahun: string;
    kategori: string;
    bidang: string;
    pengurusId: string;
    pengurus: { id: string; nama: string; jabatan: string };
    createdAt: string;
};

type PengurusOption = {
    id: string;
    nama: string;
    jabatan: string;
    divisi: string;
};

const PERIODE_OPTIONS = [
    'April-Mei',
    'Juni-Juli',
    'Agustus-September',
    'Oktober-November',
    'Desember-Januari',
];

const KATEGORI_OPTIONS = [
    { value: 'KETUA_BIDANG_TERBAIK', label: 'Ketua Bidang Terbaik' },
    { value: 'WAKIL_TERBAIK', label: 'Wakil Terbaik' },
    { value: 'STAF_TERBAIK', label: 'Staf Terbaik' },
];

const KATEGORI_LABEL: Record<string, string> = {
    KETUA_BIDANG_TERBAIK: 'Ketua Bidang Terbaik',
    WAKIL_TERBAIK: 'Wakil Terbaik',
    STAF_TERBAIK: 'Staf Terbaik',
};

export default function AwardeeClientPage({
    initialAwardees,
    pengurusList,
}: {
    initialAwardees: AwardeeWithPengurus[];
    pengurusList: PengurusOption[];
}) {
    const router = useRouter();
    const [isPending, startTransition] = useTransition();
    const [awardees, setAwardees] = useState<AwardeeWithPengurus[]>(initialAwardees);
    const [showForm, setShowForm] = useState(false);
    const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());

    // Form state
    const [periode, setPeriode] = useState('');
    const [tahun, setTahun] = useState('');
    const [kategori, setKategori] = useState('');
    const [bidang, setBidang] = useState('');
    const [pengurusId, setPengurusId] = useState('');
    const [createdAt, setCreatedAt] = useState(new Date().toISOString().split('T')[0]);
    const [isSubmitting, setIsSubmitting] = useState(false);

    // Group awardees by tahun + periode
    const grouped = awardees.reduce<Record<string, AwardeeWithPengurus[]>>((acc, a) => {
        const key = `${a.tahun} — ${a.periode}`;
        if (!acc[key]) acc[key] = [];
        acc[key].push(a);
        return acc;
    }, {});

    const toggleGroup = (key: string) => {
        setExpandedGroups((prev) => {
            const next = new Set(prev);
            if (next.has(key)) next.delete(key);
            else next.add(key);
            return next;
        });
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!periode || !tahun || !kategori || !bidang || !pengurusId) {
            toast.error('Semua field wajib diisi');
            return;
        }
        setIsSubmitting(true);
        try {
            const result = await createAwardeePH({
                periode,
                tahun,
                kategori,
                bidang,
                pengurusId,
                createdAt: createdAt ? new Date(createdAt) : undefined
            });
            if (result.success) {
                toast.success(result.message);
                setShowForm(false);
                setPeriode('');
                setTahun('');
                setKategori('');
                setBidang('');
                setPengurusId('');
                setCreatedAt(new Date().toISOString().split('T')[0]);
                startTransition(() => router.refresh());
            } else {
                toast.error(result.message);
            }
        } catch (e: any) {
            toast.error('Gagal menyimpan: ' + e.message);
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleDelete = async (id: string, nama: string) => {
        if (!confirm(`Hapus awardee ${nama}?`)) return;
        startTransition(async () => {
            const result = await deleteAwardeePH(id);
            if (result.success) {
                toast.success(result.message);
                setAwardees((prev) => prev.filter((a) => a.id !== id));
            } else {
                toast.error(result.message);
            }
        });
    };

    return (
        <div className="space-y-6">
            {/* Add Button */}
            <div className="flex justify-end">
                <Button onClick={() => setShowForm(!showForm)} variant={showForm ? 'outline' : 'default'}>
                    <Plus className="h-4 w-4 mr-2" />
                    {showForm ? 'Tutup Form' : 'Tambah Awardee'}
                </Button>
            </div>

            {/* Add Form */}
            {showForm && (
                <Card className="border-primary/30">
                    <CardHeader>
                        <CardTitle className="text-base flex items-center gap-2">
                            <Star className="h-4 w-4 text-primary" />
                            Tambah Awardee Baru
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        <form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            {/* Periode */}
                            <div className="space-y-2">
                                <Label>Periode</Label>
                                <Select value={periode} onValueChange={setPeriode}>
                                    <SelectTrigger>
                                        <SelectValue placeholder="Pilih Periode" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {PERIODE_OPTIONS.map((p) => (
                                            <SelectItem key={p} value={p}>{p}</SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>

                            {/* Tahun */}
                            <div className="space-y-2">
                                <Label>Tahun</Label>
                                <Input
                                    placeholder="Contoh: 2024"
                                    value={tahun}
                                    onChange={(e) => setTahun(e.target.value)}
                                />
                            </div>

                            {/* Kategori */}
                            <div className="space-y-2">
                                <Label>Kategori</Label>
                                <Select value={kategori} onValueChange={setKategori}>
                                    <SelectTrigger>
                                        <SelectValue placeholder="Pilih Kategori" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {KATEGORI_OPTIONS.map((k) => (
                                            <SelectItem key={k.value} value={k.value}>{k.label}</SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>

                            {/* Bidang */}
                            <div className="space-y-2">
                                <Label>Bidang / Divisi</Label>
                                <Input
                                    placeholder="Contoh: Bidang Kominfo"
                                    value={bidang}
                                    onChange={(e) => setBidang(e.target.value)}
                                />
                            </div>

                            {/* Tanggal Posting */}
                            <div className="space-y-2">
                                <Label>Tanggal Posting</Label>
                                <Input
                                    type="date"
                                    value={createdAt}
                                    onChange={(e) => setCreatedAt(e.target.value)}
                                />
                            </div>

                            {/* Pengurus Dropdown */}
                            <div className="space-y-2 md:col-span-2">
                                <Label>Pengurus</Label>
                                <Select value={pengurusId} onValueChange={setPengurusId}>
                                    <SelectTrigger>
                                        <SelectValue placeholder="Pilih Pengurus..." />
                                    </SelectTrigger>
                                    <SelectContent className="max-h-60">
                                        {pengurusList.length === 0 ? (
                                            <SelectItem value="_empty" disabled>
                                                Belum ada data pengurus
                                            </SelectItem>
                                        ) : (
                                            pengurusList.map((p) => (
                                                <SelectItem key={p.id} value={p.id}>
                                                    {p.nama} — {p.jabatan}
                                                </SelectItem>
                                            ))
                                        )}
                                    </SelectContent>
                                </Select>
                            </div>

                            <div className="md:col-span-2 flex justify-end gap-2 pt-2">
                                <Button type="button" variant="ghost" onClick={() => setShowForm(false)}>
                                    Batal
                                </Button>
                                <Button type="submit" disabled={isSubmitting || isPending}>
                                    {isSubmitting ? 'Menyimpan...' : 'Simpan Awardee'}
                                </Button>
                            </div>
                        </form>
                    </CardContent>
                </Card>
            )}

            {/* List grouped by tahun — periode */}
            {Object.keys(grouped).length === 0 ? (
                <Card>
                    <CardContent className="py-16 text-center">
                        <Trophy className="h-12 w-12 text-muted-foreground mx-auto mb-4 opacity-40" />
                        <p className="text-muted-foreground">Belum ada data awardee.</p>
                        <p className="text-sm text-muted-foreground mt-1">
                            Klik &quot;Tambah Awardee&quot; untuk menambahkan pemenang pertama.
                        </p>
                    </CardContent>
                </Card>
            ) : (
                <div className="space-y-4">
                    {Object.entries(grouped).map(([groupKey, entries]) => {
                        const isExpanded = expandedGroups.has(groupKey);
                        return (
                            <Card key={groupKey} className="overflow-hidden">
                                <button
                                    type="button"
                                    className="w-full text-left px-6 py-4 flex items-center justify-between hover:bg-muted/30 transition-colors"
                                    onClick={() => toggleGroup(groupKey)}
                                >
                                    <div className="flex items-center gap-3">
                                        <Trophy className="h-5 w-5 text-primary" />
                                        <span className="font-semibold">{groupKey}</span>
                                        <Badge variant="secondary">{entries.length} pemenang</Badge>
                                    </div>
                                    {isExpanded ? (
                                        <ChevronDown className="h-4 w-4 text-muted-foreground" />
                                    ) : (
                                        <ChevronRight className="h-4 w-4 text-muted-foreground" />
                                    )}
                                </button>

                                {isExpanded && (
                                    <div className="border-t border-border">
                                        <div className="divide-y divide-border">
                                            {entries.map((a) => (
                                                <div
                                                    key={a.id}
                                                    className="px-6 py-4 flex items-center justify-between gap-4"
                                                >
                                                    <div className="flex items-start gap-3 min-w-0">
                                                        <div className="mt-0.5">
                                                            <Badge
                                                                variant={
                                                                    a.kategori === 'KETUA_BIDANG_TERBAIK'
                                                                        ? 'default'
                                                                        : 'secondary'
                                                                }
                                                                className="text-xs whitespace-nowrap"
                                                            >
                                                                {KATEGORI_LABEL[a.kategori] ?? a.kategori}
                                                            </Badge>
                                                        </div>
                                                        <div className="min-w-0">
                                                            <p className="font-semibold text-foreground truncate">
                                                                {a.pengurus.nama}
                                                            </p>
                                                            <p className="text-sm text-muted-foreground">
                                                                {a.pengurus.jabatan} · {a.bidang}
                                                            </p>
                                                        </div>
                                                    </div>
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        className="text-destructive hover:text-destructive hover:bg-destructive/10 shrink-0"
                                                        onClick={() =>
                                                            handleDelete(a.id, a.pengurus.nama)
                                                        }
                                                        disabled={isPending}
                                                    >
                                                        <Trash2 className="h-4 w-4" />
                                                    </Button>
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                )}
                            </Card>
                        );
                    })}
                </div>
            )}
        </div>
    );
}
