'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 { Users, BookOpen, BookMarked, Layers, TrendingUp, Clock } from 'lucide-react';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell,
} from 'recharts';

interface DashboardData {
  totalSantri: number;
  totalHafalan: number;
  totalJilidSelesai: number;
  totalJilidProses: number;
  hafalanBaru: number;
  hafalanMurojaah: number;
  totalNgaji: number;
  kelasStats: { kelas: string; _count: { id: number } }[];
  kelompokStats: { kelompokBacaan: string; _count: { id: number } }[];
  recentHafalan: { id: string; surah: string; ayatMulai: number; ayatAkhir: number; status: string; tanggal: string; santri: { nama: string; kelas: string } }[];
  recentNgaji: { id: string; juz: number; halamanMulai: number; halamanAkhir: number; tanggal: string; santri: { nama: string; kelas: string } }[];
}

const COLORS = ['#059669', '#0d9488', '#d97706', '#dc2626', '#7c3aed'];

export default function DashboardPage() {
  const { token } = useAppStore();
  const [data, setData] = useState<DashboardData | 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 dashboard.</p>;

  const stats = [
    { label: 'Total Santri', value: data.totalSantri, icon: <Users className="w-5 h-5" />, color: 'bg-emerald-100 text-emerald-700' },
    { label: 'Hafalan Kuat', value: data.totalHafalan, icon: <BookOpen className="w-5 h-5" />, color: 'bg-teal-100 text-teal-700' },
    { label: 'Jilid Selesai', value: data.totalJilidSelesai, icon: <Layers className="w-5 h-5" />, color: 'bg-amber-100 text-amber-700' },
    { label: 'Jilid Proses', value: data.totalJilidProses, icon: <TrendingUp className="w-5 h-5" />, color: 'bg-purple-100 text-purple-700' },
  ];

  const pieData = [
    { name: 'Kuat', value: data.totalHafalan },
    { name: 'Muroja\'ah', value: data.hafalanMurojaah },
    { name: 'Baru', value: data.hafalanBaru },
  ];

  const kelasChartData = data.kelasStats.map((k) => ({ name: k.kelas, santri: k._count.id }));

  const kelompokChartData = data.kelompokStats.map((k) => ({ name: k.kelompokBacaan, santri: k._count.id }));

  const statusBadge = (status: string) => {
    const map: Record<string, string> = {
      KUAT: 'bg-emerald-100 text-emerald-800',
      "MUROJA'AH": 'bg-amber-100 text-amber-800',
      BARU: 'bg-blue-100 text-blue-800',
    };
    return map[status] || 'bg-gray-100 text-gray-800';
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-xl font-bold text-gray-900">Dashboard</h1>
        <p className="text-sm text-gray-500">Ringkasan progres santri Anda</p>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4">
        {stats.map((s) => (
          <Card key={s.label} className="border-0 shadow-sm">
            <CardContent className="p-4">
              <div className="flex items-center gap-3">
                <div className={`w-10 h-10 rounded-xl flex items-center justify-center ${s.color}`}>
                  {s.icon}
                </div>
                <div>
                  <p className="text-2xl font-bold text-gray-900">{s.value}</p>
                  <p className="text-xs text-gray-500">{s.label}</p>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Charts Row */}
      <div className="grid md:grid-cols-3 gap-4">
        {/* Hafalan Distribution */}
        <Card className="border-0 shadow-sm">
          <CardHeader className="pb-2 px-4 pt-4">
            <CardTitle className="text-sm font-semibold">Distribusi Hafalan</CardTitle>
          </CardHeader>
          <CardContent className="px-4 pb-4">
            <ResponsiveContainer width="100%" height={200}>
              <PieChart>
                <Pie data={pieData} cx="50%" cy="50%" innerRadius={50} outerRadius={80} paddingAngle={3} dataKey="value">
                  {pieData.map((_, i) => (
                    <Cell key={i} fill={COLORS[i]} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
            <div className="flex justify-center gap-3 text-xs">
              {pieData.map((d, i) => (
                <div key={d.name} className="flex items-center gap-1">
                  <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: COLORS[i] }} />
                  <span className="text-gray-600">{d.name} ({d.value})</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Kelas Chart */}
        <Card className="border-0 shadow-sm">
          <CardHeader className="pb-2 px-4 pt-4">
            <CardTitle className="text-sm font-semibold">Santri per Kelas</CardTitle>
          </CardHeader>
          <CardContent className="px-4 pb-4">
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={kelasChartData}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} />
                <XAxis dataKey="name" tick={{ fontSize: 11 }} />
                <YAxis allowDecimals={false} tick={{ fontSize: 11 }} />
                <Tooltip />
                <Bar dataKey="santri" fill="#059669" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Kelompok Chart */}
        <Card className="border-0 shadow-sm">
          <CardHeader className="pb-2 px-4 pt-4">
            <CardTitle className="text-sm font-semibold">Kelompok Bacaan</CardTitle>
          </CardHeader>
          <CardContent className="px-4 pb-4">
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={kelompokChartData} layout="vertical">
                <CartesianGrid strokeDasharray="3 3" horizontal={false} />
                <XAxis type="number" allowDecimals={false} tick={{ fontSize: 11 }} />
                <YAxis type="category" dataKey="name" tick={{ fontSize: 11 }} width={80} />
                <Tooltip />
                <Bar dataKey="santri" fill="#0d9488" radius={[0, 4, 4, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>

      {/* Recent Activity */}
      <div className="grid md:grid-cols-2 gap-4">
        <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" />
              Hafalan Terbaru
            </CardTitle>
          </CardHeader>
          <CardContent className="px-4 pb-4">
            <div className="space-y-2 max-h-64 overflow-y-auto">
              {data.recentHafalan.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.santri.nama}</p>
                    <p className="text-xs text-gray-500">{h.surah}: {h.ayatMulai}-{h.ayatAkhir}</p>
                  </div>
                  <Badge variant="secondary" className={statusBadge(h.status)}>
                    {h.status}
                  </Badge>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        <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" />
              Ngaji Terbaru
            </CardTitle>
          </CardHeader>
          <CardContent className="px-4 pb-4">
            <div className="space-y-2 max-h-64 overflow-y-auto">
              {data.recentNgaji.map((n) => (
                <div key={n.id} className="flex items-center justify-between py-2 border-b last:border-0">
                  <div>
                    <p className="text-sm font-medium text-gray-900">{n.santri.nama}</p>
                    <p className="text-xs text-gray-500">
                      Juz {n.juz} — Hlm {n.halamanMulai}-{n.halamanAkhir}
                    </p>
                  </div>
                  <div className="flex items-center gap-1 text-xs text-gray-500">
                    <Clock className="w-3 h-3" />
                    {new Date(n.tanggal).toLocaleDateString('id-ID')}
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

function LoadingSkeleton() {
  return (
    <div className="space-y-6">
      <div>
        <div className="h-6 w-32 bg-gray-200 rounded animate-pulse" />
        <div className="h-4 w-48 bg-gray-200 rounded animate-pulse mt-2" />
      </div>
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {Array.from({ length: 4 }).map((_, i) => (
          <Card key={i} className="border-0 shadow-sm">
            <CardContent className="p-4">
              <div className="h-10 w-10 bg-gray-200 rounded-xl animate-pulse" />
              <div className="h-6 w-16 bg-gray-200 rounded animate-pulse mt-3" />
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}