'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { PageHeader } from '@/components/common/PageHeader';
import { StatCard } from '@/components/common/StatCard';
import { getCurrentUserSync } from '@/lib/api/auth';
import { TSessionUser } from '@/types/auth';
import { TPrestasi } from '@/types/domain';
import axios from 'axios';
import { CheckSquare, Clock, AlertTriangle, Users, Award, ArrowRight, TrendingUp } from 'lucide-react';
import { formatDate } from '@/lib/utils';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';

export default function OperatorDashboard() {
  const [user, setUser] = useState<TSessionUser | null>(null);
  const [list, setList] = useState<TPrestasi[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const session = getCurrentUserSync();
    if (session) {
      setUser(session);
      loadPrestasi(session.perguruanTinggiName || '');
    }
  }, []);

  async function loadPrestasi(ptName: string) {
    setIsLoading(true);
    try {
      const res = await axios.get('/api/prestasi');
      if (res.data.success && res.data.data) {
        const mapped = res.data.data.map((item: any) => {
          let studentName = 'Gilang Arya Mahmudi';
          let studentNim = '2211011069';
          try {
            if (item.keterangan && (item.keterangan.trim().startsWith('{') || item.keterangan.trim().startsWith('['))) {
              const parsed = JSON.parse(item.keterangan);
              if (parsed.mahasiswa && parsed.mahasiswa.length > 0) {
                studentNim = parsed.mahasiswa[0].nim || studentNim;
                studentName = parsed.mahasiswa[0].nama || studentName;
              }
            }
          } catch (e) {
            // fallback
          }

          let uiStatus: 'Submitted' | 'Draft' | 'Approved' | 'Rejected' = 'Submitted';
          if (item.status === 'draft') uiStatus = 'Draft';
          else if (item.status === 'menunggu_verifikasi') uiStatus = 'Submitted';
          else if (item.status === 'terverifikasi') uiStatus = 'Approved';
          else if (item.status === 'ditolak') uiStatus = 'Rejected';

          return {
            id: item.id,
            mahasiswaId: item.mahasiswa_id,
            mahasiswaName: studentName,
            nim: studentNim,
            jenisKegiatan: item.jenis_kegiatan,
            namaKegiatan: item.nama_kegiatan,
            penyelenggara: item.penyelenggara,
            tingkat: item.tingkat ? (item.tingkat.charAt(0).toUpperCase() + item.tingkat.slice(1)) : 'Nasional',
            capaian: item.capaian,
            tanggalKegiatan: item.tanggal_kegiatan,
            dokumenPath: item.dokumen_path,
            dokumenName: item.dokumen_name,
            status: uiStatus,
            createdAt: item.created_at || new Date().toISOString(),
          };
        });
        setList(mapped);
      }
    } catch (e) {
      console.error(e);
    } finally {
      setIsLoading(false);
    }
  }

  if (!user) {
    return (
      <div className="flex items-center justify-center min-h-[50vh]">
        <span className="text-sm text-text-muted font-bold">Memuat data pengguna...</span>
      </div>
    );
  }

  const queue = list.filter((p) => p.status === 'menunggu_verifikasi');
  const verifiedCount = list.filter((p) => p.status === 'terverifikasi').length;
  const rejectedCount = list.filter((p) => p.status === 'ditolak').length;

  const chartData = [
    { day: 'Sen', setuju: 4, tolak: 1 },
    { day: 'Sel', setuju: 8, tolak: 3 },
    { day: 'Rab', setuju: 12, tolak: 2 },
    { day: 'Kam', setuju: 7, tolak: 4 },
    { day: 'Jum', setuju: 15, tolak: 1 },
    { day: 'Sab', setuju: 10, tolak: 2 },
    { day: 'Min', setuju: 5, tolak: 0 },
  ];

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <PageHeader
        title={`Dashboard Operator ${user.perguruanTinggiName}`}
        description="Portal monitoring, verifikasi berkas fisik prestasi mahasiswa, dan laporan kinerja kampus."
      />

      {/* Stats Cards Row */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
        <StatCard
          title="Mahasiswa Terdaftar"
          value="1,240"
          description="Total mahasiswa aktif PT"
          icon={Users}
        />
        <StatCard
          title="Antrian Verifikasi"
          value={queue.length}
          description="Berkas menunggu direview"
          icon={Clock}
          className="hover:border-warning/20"
        />
        <StatCard
          title="Total Terverifikasi"
          value={verifiedCount}
          description="Capaian disetujui"
          icon={CheckSquare}
          className="hover:border-success/20"
        />
        <StatCard
          title="Total Ditolak"
          value={rejectedCount}
          description="Berkas tidak valid"
          icon={AlertTriangle}
          className="hover:border-danger/20"
        />
      </div>

      {/* Trend Chart Row */}
      <div className="bg-white border border-slate-100 rounded-3xl p-6 shadow-[0_10px_30px_rgba(0,0,0,0.02)] space-y-4">
        <div className="flex items-center justify-between pb-2 border-b border-slate-100">
          <div className="flex items-center gap-2 text-slate-800">
            <TrendingUp className="h-5 w-5 text-[#f06424]" />
            <h4 className="font-extrabold text-slate-800">Tren Aktivitas Verifikasi Berkas (Mingguan)</h4>
          </div>
          <span className="text-[10px] bg-emerald-500/10 text-emerald-600 px-2.5 py-1 rounded-full font-bold uppercase tracking-wider">
            7 Hari Terakhir
          </span>
        </div>
        
        <div className="h-64 w-full pt-4">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={chartData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
              <defs>
                <linearGradient id="colorVerif" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#10B981" stopOpacity={0.2}/>
                  <stop offset="95%" stopColor="#10B981" stopOpacity={0.0}/>
                </linearGradient>
                <linearGradient id="colorDitolak" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#EF4444" stopOpacity={0.2}/>
                  <stop offset="95%" stopColor="#EF4444" stopOpacity={0.0}/>
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
              <XAxis dataKey="day" tickLine={false} axisLine={false} tick={{ fill: '#94a3b8', fontSize: 10, fontWeight: 600 }} />
              <YAxis tickLine={false} axisLine={false} tick={{ fill: '#94a3b8', fontSize: 10, fontWeight: 600 }} />
              <Tooltip 
                contentStyle={{ 
                  backgroundColor: '#ffffff', 
                  borderRadius: '12px', 
                  border: '1px solid #e2e8f0', 
                  boxShadow: '0 4px 20px rgb(0,0,0,0.03)' 
                }}
                itemStyle={{ fontWeight: 'bold' }}
              />
              <Area type="monotone" name="Disetujui" dataKey="setuju" stroke="#10B981" strokeWidth={2.5} fillOpacity={1} fill="url(#colorVerif)" />
              <Area type="monotone" name="Ditolak" dataKey="tolak" stroke="#EF4444" strokeWidth={2.5} fillOpacity={1} fill="url(#colorDitolak)" />
            </AreaChart>
          </ResponsiveContainer>
        </div>
      </div>

      {/* Layout Content */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
        
        {/* Verification Queue (Table-like Summary) */}
        <div className="lg:col-span-8 bg-card border border-text-muted/10 rounded-3xl p-6 shadow-sm space-y-4">
          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <h3 className="text-base font-bold text-text-primary">Antrian Verifikasi Terbaru</h3>
              <p className="text-xs text-text-muted font-medium">Berkas prestasi mahasiswa yang perlu diperiksa.</p>
            </div>
            {queue.length > 0 && (
              <Link
                href="/dashboard/operator/verifikasi"
                className="inline-flex items-center gap-1 text-xs font-bold text-primary hover:underline"
              >
                Lihat Semua Antrian
                <ArrowRight className="h-3.5 w-3.5" />
              </Link>
            )}
          </div>

          <div className="overflow-x-auto pt-2">
            {isLoading ? (
              <div className="space-y-3 animate-pulse">
                {[1, 2].map((i) => (
                  <div key={i} className="h-12 bg-text-muted/5 rounded-xl" />
                ))}
              </div>
            ) : queue.length > 0 ? (
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="border-b border-text-muted/10 bg-surface/50 text-[10px] uppercase font-bold text-text-muted">
                    <th className="px-4 py-3">Nama/NIM</th>
                    <th className="px-4 py-3">Prestasi</th>
                    <th className="px-4 py-3">Tanggal Diajukan</th>
                    <th className="px-4 py-3 text-right">Aksi</th>
                  </tr>
                </thead>
                <tbody>
                  {queue.slice(0, 5).map((item) => (
                    <tr key={item.id} className="border-b border-text-muted/5 hover:bg-surface/30 transition-colors text-xs">
                      <td className="px-4 py-4">
                        <span className="font-bold text-text-primary block">{item.mahasiswaName}</span>
                        <span className="text-[10px] text-text-muted">{item.nim}</span>
                      </td>
                      <td className="px-4 py-4 font-semibold text-text-primary">
                        <span className="block truncate max-w-[200px]">{item.namaKegiatan}</span>
                        <span className="text-[10px] text-primary bg-primary/5 px-1.5 py-0.5 rounded uppercase font-bold">{item.tingkat}</span>
                      </td>
                      <td className="px-4 py-4 text-text-muted font-medium">
                        {formatDate(item.createdAt)}
                      </td>
                      <td className="px-4 py-4 text-right">
                        <Link
                          href={`/dashboard/operator/verifikasi/${item.id}`}
                          className="inline-flex items-center gap-1 px-3 py-1.5 bg-primary hover:bg-primary-dark text-white rounded-lg text-[10px] font-bold shadow-sm"
                        >
                          Review
                        </Link>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            ) : (
              <div className="text-center py-8 text-xs font-semibold text-text-muted">
                Semua berkas pengajuan telah terverifikasi. Antrian bersih!
              </div>
            )}
          </div>
        </div>

        {/* Quick Info card */}
        <div className="lg:col-span-4 bg-card border border-text-muted/10 rounded-3xl p-6 space-y-4 shadow-sm">
          <div className="flex items-center gap-2.5 text-primary border-b border-text-muted/5 pb-3">
            <Award className="h-5 w-5" />
            <h4 className="font-bold text-text-primary">Rekapitulasi Kinerja</h4>
          </div>

          <div className="space-y-4">
            <div className="space-y-1">
              <div className="flex justify-between text-xs font-semibold text-text-muted">
                <span>Rasio Kelulusan Berkas</span>
                <span className="text-text-primary font-bold">
                  {list.length > 0 ? Math.round((verifiedCount / (verifiedCount + rejectedCount || 1)) * 100) : 0}%
                </span>
              </div>
              <div className="h-2 w-full bg-surface rounded-full overflow-hidden border">
                <div 
                  className="h-full bg-success" 
                  style={{ width: `${list.length > 0 ? (verifiedCount / (verifiedCount + rejectedCount || 1)) * 100 : 0}%` }}
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4 text-xs font-semibold pt-2 border-t border-text-muted/5">
              <div>
                <span className="block text-[10px] text-text-muted uppercase">Prestasi Internasional</span>
                <span className="text-text-primary text-base font-extrabold">{list.filter((p) => p.tingkat === 'Internasional' && p.status === 'terverifikasi').length}</span>
              </div>
              <div>
                <span className="block text-[10px] text-text-muted uppercase">Prestasi Nasional</span>
                <span className="text-text-primary text-base font-extrabold">{list.filter((p) => p.tingkat === 'Nasional' && p.status === 'terverifikasi').length}</span>
              </div>
            </div>
          </div>
        </div>

      </div>
    </div>
  );
}
