'use client';

import { useAppStore } from '@/stores/app-store';
import { useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { BookOpen, BookMarked, Layers, GraduationCap, TrendingUp, CheckCircle2 } from 'lucide-react';
import { Progress } from '@/components/ui/progress';

const JILID_OPTIONS = ['Jilid 1', 'Jilid 2', 'Jilid 3', 'Jilid 4', 'Jilid 5', 'Jilid 6', 'Ghorib', 'Tajwid Dasar'];
const TOTAL_JILID = JILID_OPTIONS.length;

interface OrtuData {
  totalHafalan: number;
  hafalanKuat: number;
  hafalanBaru: number;
  hafalanMurojaah: number;
  totalNgaji: number;
  jilidSelesai: number;
  jilidProses: number;
  jilid: { id: string; namaJilid: string; halaman: number | null; status: string; tanggalSelesai: string | null; catatanGuru: string | null }[];
  hafalanList: { id: string; surah: string; ayatMulai: number; ayatAkhir: number; status: string; tanggal: string; catatan: string | null }[];
  ngajiList: { id: string; juz: number; halamanMulai: number; halamanAkhir: number; tanggal: string; kualitas: string; catatan: string | null }[];
}

export default function OrtuDashboard() {
  const { user, token } = useAppStore();
  const [data, setData] = useState<OrtuData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!token) return;
    fetch('/api/dashboard', { headers: { Authorization: `Bearer ${token}` } })
      .then((r) => r.json())
      .then((d) => { setData(d); setLoading(false); })
      .catch(() => setLoading(false));
  }, [token]);

  if (loading) return <LoadingSkeleton />;
  if (!data) return <p className="text-gray-500">Gagal memuat data.</p>;

  const progress = (data.jilidSelesai / TOTAL_JILID) * 100;
  const statusColor = (s: string) => {
    const map: Record<string, string> = {
      KUAT: 'bg-emerald-100 text-emerald-800',
      "MUROJA'AH": 'bg-amber-100 text-amber-800',
      BARU: 'bg-sky-100 text-sky-800',
    };
    return map[s] || 'bg-gray-100 text-gray-800';
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="bg-emerald-600 rounded-2xl p-5 text-white">
        <div className="flex items-center gap-3 mb-2">
          <div className="w-12 h-12 rounded-full bg-white/20 flex items-center justify-center">
            <BookOpen className="w-6 h-6" />
          </div>
          <div>
            <h1 className="text-lg font-bold">Assalamu&apos;alaikum!</h1>
            <p className="text-emerald-100 text-sm">Progres {user?.nama}</p>
          </div>
        </div>
        <div className="grid grid-cols-2 gap-3 mt-4">
          <div className="bg-white/10 rounded-xl p-3">
            <p className="text-2xl font-bold">{data.jilidSelesai}</p>
            <p className="text-emerald-100 text-xs">Jilid Selesai</p>
          </div>
          <div className="bg-white/10 rounded-xl p-3">
            <p className="text-2xl font-bold">{data.hafalanKuat}</p>
            <p className="text-emerald-100 text-xs">Hafalan Kuat</p>
          </div>
        </div>
      </div>

      {/* Info Card */}
      <Card className="border-0 shadow-sm">
        <CardContent className="p-4">
          <div className="flex items-center gap-2 text-sm text-gray-600">
            <GraduationCap className="w-4 h-4" />
            <span>Kelas <strong>{user?.kelas}</strong> — Kelompok <strong>{user?.kelompokBacaan}</strong></span>
          </div>
          <div className="flex items-center gap-2 text-sm text-gray-600 mt-1">
            <span>Guru: <strong>{user?.guruNama}</strong></span>
          </div>
        </CardContent>
      </Card>

      {/* Progres Khatam */}
      <Card className="border-0 shadow-sm">
        <CardHeader className="pb-2 px-4 pt-4">
          <CardTitle className="text-sm font-semibold flex items-center gap-2">
            <TrendingUp className="w-4 h-4 text-emerald-600" />
            Progres Jilid ({TOTAL_JILID} Jilid)
          </CardTitle>
        </CardHeader>
        <CardContent className="px-4 pb-4">
          <div className="flex items-center justify-between mb-2">
            <p className="text-sm text-gray-600">{data.jilidSelesai} dari {TOTAL_JILID} jilid selesai</p>
            <p className="text-sm font-bold text-emerald-600">{progress.toFixed(0)}%</p>
          </div>
          <Progress value={progress} className="h-3" />
          <div className="grid grid-cols-4 sm:grid-cols-4 md:grid-cols-8 gap-1.5 mt-4">
            {JILID_OPTIONS.map((jilidName) => {
              const jilid = data.jilid.find((j) => j.namaJilid === jilidName);
              const status = jilid?.status || 'BELUM';
              const bg = status === 'SELESAI' ? 'bg-emerald-500' : status === 'PROSES' ? 'bg-amber-400' : 'bg-gray-200';
              const label = jilidName.startsWith('Jilid ') ? jilidName.replace('Jilid ', 'J') : jilidName;
              return (
                <div key={jilidName} className={`aspect-square rounded-lg ${bg} flex items-center justify-center`}>
                  <span className="text-[10px] font-semibold text-white leading-tight text-center">{label}</span>
                </div>
              );
            })}
          </div>
        </CardContent>
      </Card>

      {/* Hafalan Terbaru */}
      <Card className="border-0 shadow-sm">
        <CardHeader className="pb-2 px-4 pt-4">
          <CardTitle className="text-sm font-semibold flex items-center gap-2">
            <BookOpen className="w-4 h-4 text-emerald-600" />
            Daftar Hafalan ({data.totalHafalan})
          </CardTitle>
        </CardHeader>
        <CardContent className="px-4 pb-4">
          <div className="flex gap-3 mb-3 text-xs">
            <span className="text-emerald-600 font-medium">{data.hafalanKuat} Kuat</span>
            <span className="text-amber-600 font-medium">{data.hafalanMurojaah} Muroja&apos;ah</span>
            <span className="text-sky-600 font-medium">{data.hafalanBaru} Baru</span>
          </div>
          <div className="space-y-2 max-h-72 overflow-y-auto">
            {data.hafalanList.map((h) => (
              <div key={h.id} className="flex items-center justify-between py-2 border-b last:border-0">
                <div>
                  <p className="text-sm font-medium text-gray-900">{h.surah}: {h.ayatMulai}–{h.ayatAkhir}</p>
                  <p className="text-xs text-gray-500">{new Date(h.tanggal).toLocaleDateString('id-ID')}</p>
                </div>
                <Badge variant="secondary" className={statusColor(h.status)}>{h.status}</Badge>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Ngaji Terbaru */}
      <Card className="border-0 shadow-sm">
        <CardHeader className="pb-2 px-4 pt-4">
          <CardTitle className="text-sm font-semibold flex items-center gap-2">
            <BookMarked className="w-4 h-4 text-teal-600" />
            Riwayat Ngaji ({data.totalNgaji})
          </CardTitle>
        </CardHeader>
        <CardContent className="px-4 pb-4">
          <div className="space-y-2 max-h-64 overflow-y-auto">
            {data.ngajiList.map((n) => (
              <div key={n.id} className="flex items-center justify-between py-2 border-b last:border-0">
                <div>
                  <p className="text-sm text-gray-900">
                    Juz <span className="font-medium">{n.juz}</span> — Hlm {n.halamanMulai}–{n.halamanAkhir}
                  </p>
                  <p className="text-xs text-gray-500">{new Date(n.tanggal).toLocaleDateString('id-ID')}</p>
                </div>
                <Badge variant="outline" className={
                  n.kualitas === 'BAIK_SEKALI' ? 'bg-emerald-100 text-emerald-800 border-emerald-200' :
                  n.kualitas === 'BAIK' ? 'bg-sky-100 text-sky-800 border-sky-200' :
                  'bg-amber-100 text-amber-800 border-amber-200'
                }>
                  {n.kualitas === 'BAIK_SEKALI' ? 'Baik Sekali' : n.kualitas === 'BAIK' ? 'Baik' : 'Cukup'}
                </Badge>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function LoadingSkeleton() {
  return (
    <div className="space-y-4">
      <div className="h-40 bg-gray-200 rounded-2xl animate-pulse" />
      <div className="h-20 bg-gray-200 rounded-xl animate-pulse" />
    </div>
  );
}