'use client';

import React, { useState } from 'react';
import { Users, CreditCard, AlertCircle, ArrowUpRight, TrendingUp, Loader2 } from 'lucide-react';
import Link from 'next/link';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';

const chartData = [
  { name: 'Jul', revenue: 40 },
  { name: 'Ags', revenue: 70 },
  { name: 'Sep', revenue: 45 },
  { name: 'Okt', revenue: 90 },
  { name: 'Nov', revenue: 65 },
  { name: 'Des', revenue: 80 },
  { name: 'Jan', revenue: 50 },
  { name: 'Feb', revenue: 85 },
  { name: 'Mar', revenue: 30 },
  { name: 'Apr', revenue: 0 },
  { name: 'Mei', revenue: 0 },
  { name: 'Jun', revenue: 0 },
];

export default function AdminDashboard() {
  const [isCreatingInvoice, setIsCreatingInvoice] = useState(false);
  const [isExporting, setIsExporting] = useState(false);

  const handleCreateInvoice = () => {
    setIsCreatingInvoice(true);
    setTimeout(() => setIsCreatingInvoice(false), 1500);
  };

  const handleExport = () => {
    setIsExporting(true);
    setTimeout(() => setIsExporting(false), 1500);
  };

  return (
    <div className="space-y-6 max-w-7xl mx-auto">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h1 className="text-2xl font-bold text-slate-900 tracking-tight">Dashboard Admin</h1>
          <p className="text-slate-500 text-sm mt-1">Ringkasan aktivitas dan pengelolaan sistem e-Payment.</p>
        </div>
        <div className="flex gap-3">
          <button 
            onClick={handleExport}
            disabled={isExporting}
            className="flex items-center gap-2 bg-white border border-slate-200 text-slate-700 px-4 py-2 rounded-lg text-sm font-medium hover:bg-slate-50 disabled:opacity-70 transition-colors"
          >
            {isExporting ? <Loader2 className="w-4 h-4 animate-spin" /> : null}
            {isExporting ? 'Mengekspor...' : 'Export Laporan'}
          </button>
          <button 
            onClick={handleCreateInvoice}
            disabled={isCreatingInvoice}
            className="flex items-center gap-2 bg-emerald-700 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-emerald-800 disabled:opacity-70 transition-colors shadow-sm"
          >
            {isCreatingInvoice ? <Loader2 className="w-4 h-4 animate-spin" /> : null}
            {isCreatingInvoice ? 'Memproses...' : 'Buat Tagihan Baru'}
          </button>
        </div>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 shrink-0">
        <StatsCard 
          title="Total Siswa Aktif" 
          value="1,248" 
          change="+12 siswa baru" 
          changeType="positive"
          icon={Users}
          color="emerald"
        />
        <StatsCard 
          title="Pemasukan Bulan Ini" 
          value="Rp 85.4M" 
          change="+15% dari bulan lalu" 
          changeType="positive"
          icon={TrendingUp}
          color="amber"
        />
        <StatsCard 
          title="Menunggu Verifikasi" 
          value="42" 
          change="Membutuhkan aksi" 
          changeType="neutral"
          icon={CreditCard}
          color="blue"
        />
        <StatsCard 
          title="Total Tunggakan" 
          value="Rp 12.5M" 
          change="-5% dari bulan lalu" 
          changeType="positive" // Positive because it reduced
          icon={AlertCircle}
          color="red"
        />
      </div>

      <div className="grid lg:grid-cols-3 gap-4">
        {/* Main Chart Area (HTML/CSS Mock since recharts isn't installed) */}
        <div className="lg:col-span-2 bg-white rounded-xl shadow-sm border border-slate-200 p-6">
          <div className="flex justify-between items-center mb-6">
            <h3 className="font-bold text-slate-800">Statistik Pembayaran Bulanan</h3>
            <select className="text-sm border border-slate-200 rounded-md px-2 py-1 bg-slate-50">
              <option>Tahun Ajaran 2024/2025</option>
            </select>
          </div>
          <div className="h-64 pt-4">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={chartData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#E2E8F0" />
                <XAxis dataKey="name" axisLine={false} tickLine={false} tick={{ fontSize: 12, fill: '#64748B' }} dy={10} />
                <YAxis axisLine={false} tickLine={false} tick={{ fontSize: 12, fill: '#64748B' }} tickFormatter={(value) => `${value}M`} />
                <Tooltip 
                  cursor={{ fill: '#F1F5F9' }}
                  contentStyle={{ borderRadius: '8px', border: 'none', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)' }}
                  formatter={(value) => [`Rp ${value} Juta`, 'Pendapatan']}
                />
                <Bar dataKey="revenue" fill="#059669" radius={[4, 4, 0, 0]} barSize={32} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>

        {/* Quick Actions & Recent Activity */}
        <div className="flex flex-col gap-4">
          <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-4 flex-1 flex flex-col">
            <h3 className="font-bold text-slate-800 text-sm mb-4">Aktivitas Terakhir</h3>
            <div className="space-y-4 flex-1">
              {[
                { title: 'Pembayaran SPP Disetujui', desc: 'Oleh Bendahara untuk Siswa: Budi (X-A)', time: '10 mnt lalu', color: 'bg-emerald-50 text-emerald-600' },
                { title: 'Wali Murid Mendaftar', desc: 'Akun baru: walimurid_x@email.com', time: '1 jam lalu', color: 'bg-blue-50 text-blue-600' },
                { title: 'Tagihan Ujian Dibuat', desc: 'Untuk seluruh siswa kelas XII', time: '3 jam lalu', color: 'bg-amber-50 text-amber-600' },
                { title: 'Backup Database', desc: 'Sistem berhasil dicadangkan', time: '1 hari lalu', color: 'bg-slate-100 text-slate-600' },
              ].map((activity, i) => (
                <div key={i} className="flex gap-3">
                  <div className={`mt-1 w-2.5 h-2.5 rounded-full shrink-0 ${activity.color.split(' ')[1].replace('text-', 'bg-')}`} />
                  <div>
                    <p className="text-xs font-bold text-slate-800">{activity.title}</p>
                    <p className="text-[10px] text-slate-500 mt-0.5">{activity.desc}</p>
                    <p className="text-[10px] text-slate-400 mt-1">{activity.time}</p>
                  </div>
                </div>
              ))}
            </div>
            <Link href="/dashboard/admin/logs" className="w-full mt-4 py-2 text-[10px] font-bold text-emerald-700 bg-emerald-50 hover:bg-emerald-100 transition-colors uppercase rounded ml-0 flex justify-center items-center">
              Lihat Semua Aktivitas
            </Link>
          </div>

          <div className="bg-[#B45309] text-white p-4 rounded-xl shadow-lg shadow-amber-900/10 shrink-0">
            <div className="flex justify-between items-start mb-2">
              <p className="text-[10px] font-bold uppercase tracking-wider opacity-80">Aksi Cepat</p>
            </div>
            <h5 className="text-sm font-bold mb-3">Buat Tagihan Baru</h5>
            <button 
              onClick={handleCreateInvoice}
              disabled={isCreatingInvoice}
              className="w-full bg-white text-amber-700 py-2 rounded-lg text-xs font-bold hover:bg-amber-50 disabled:opacity-70 flex items-center justify-center gap-2 transition-colors"
            >
              {isCreatingInvoice ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : null}
              {isCreatingInvoice ? 'Sedang Memproses...' : 'Mulai Sekarang'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function StatsCard({ title, value, change, changeType, icon: Icon, color }: any) {
  const colorMap: any = {
    emerald: 'bg-emerald-50 text-emerald-600',
    amber: 'bg-amber-50 text-amber-600',
    blue: 'bg-blue-50 text-blue-600',
    red: 'bg-red-50 text-red-600'
  };

  const textMap: any = {
    emerald: 'text-emerald-600',
    amber: 'text-amber-600',
    blue: 'text-blue-600',
    red: 'text-red-600'
  }

  return (
    <div className={`bg-white p-4 rounded-xl border border-slate-200 flex items-center gap-4 shadow-sm ${color === 'amber' ? 'border-l-4 border-l-amber-500' : ''}`}>
      <div className={`w-12 h-12 rounded-lg flex items-center justify-center ${colorMap[color]}`}>
        <Icon className="h-6 w-6" />
      </div>
      <div>
        <p className="text-xs text-slate-500 font-medium">{title}</p>
        <h3 className="text-xl font-bold text-slate-900">{value}</h3>
        <p className={`text-[10px] ${textMap[color]}`}>
          {change}
        </p>
      </div>
    </div>
  )
}
