'use client';

import { useState, useEffect } from 'react';
import { useCurrency } from '@/lib/hooks/useCurrency';
import { useTranslations } from 'next-intl';
import { usePathname, useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import {
  FiDollarSign, FiArrowUp, FiArrowDown, FiShoppingCart,
  FiCalendar, FiTrendingUp, FiBook, FiAward, FiCheckCircle,
  FiAlertCircle, FiClock,
} from 'react-icons/fi';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, RadialBarChart, RadialBar } from 'recharts';
import apiClient, { API_CONFIG } from '@/lib/api';
import { useAuth } from '@/lib/hooks/useAuth';
import { ProtectedRoute } from '@/components/auth/ProtectedRoute';

interface WalletData { balance: number; daily_spent: number; daily_limit: number }
interface Transaction { id: number; type: string; amount: number; balance_after: number; description: string; created_at: string }
interface AttendanceSummary { total: number; present: number; late: number; absent: number; leave: number; sick: number; attendance_rate: number }
interface KpiData { score: number; attendance_score: number; behavior_score: number; rank: number }
interface GradeItem { subject: { name: string }; final_grade: number | null; grade_letter: string | null }

export default function StudentDashboardPage() {
  const { formatMoney } = useCurrency();
  const t = useTranslations();
  const pathname = usePathname();
  const router = useRouter();
  const { user } = useAuth();

  const [wallet, setWallet] = useState<WalletData | null>(null);
  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [attendance, setAttendance] = useState<AttendanceSummary | null>(null);
  const [kpi, setKpi] = useState<KpiData | null>(null);
  const [grades, setGrades] = useState<GradeItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [studentId, setStudentId] = useState<number | null>(null);

  const localeMatch = pathname?.match(/^\/(id|en|th|ms)/);
  const locale = localeMatch ? localeMatch[1] : 'id';
  const lp = (path: string) => `/${locale}${path}`;

  useEffect(() => { fetchAll(); }, []);

  const fetchAll = async () => {
    try {
      setLoading(true);
      const meRes = await apiClient.get(API_CONFIG.endpoints.auth.me);
      const sid = meRes.data.data?.student?.id;
      const userId = meRes.data.data?.id;
      if (!sid) return;
      setStudentId(sid);

      const currentYear = `${new Date().getFullYear()}/${new Date().getFullYear() + 1}`;
      const startOfMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().split('T')[0];
      const today = new Date().toISOString().split('T')[0];

      const [walletRes, txRes, attendRes, kpiRes, gradesRes] = await Promise.allSettled([
        apiClient.get(API_CONFIG.endpoints.wallet.balance(sid)),
        apiClient.get(API_CONFIG.endpoints.wallet.transactions(sid), { params: { per_page: 10 } }),
        apiClient.get(API_CONFIG.endpoints.studentAttendance.my, { params: { start_date: startOfMonth, end_date: today } }),
        apiClient.get('/api/v1/kpi/me'),
        apiClient.get(API_CONFIG.endpoints.grades.studentReport(sid), { params: { academic_year: currentYear } }),
      ]);

      if (walletRes.status === 'fulfilled') setWallet(walletRes.value.data.data);
      if (txRes.status === 'fulfilled') {
        // getTransactions returns a Laravel paginator: data.data = { data: [...], current_page, ... }
        const txPayload = txRes.value.data.data;
        setTransactions(Array.isArray(txPayload) ? txPayload : (txPayload?.data ?? []));
      }
      if (attendRes.status === 'fulfilled') setAttendance(attendRes.value.data.data?.summary);
      if (kpiRes.status === 'fulfilled') setKpi(kpiRes.value.data.data?.kpi_score);
      if (gradesRes.status === 'fulfilled') {
        const bySem = gradesRes.value.data.data?.by_semester;
        if (bySem && typeof bySem === 'object' && !Array.isArray(bySem)) {
          const allGrades = Object.values(bySem).flatMap((s: any) => (Array.isArray(s?.grades) ? s.grades : []));
          setGrades(allGrades.slice(0, 6));
        }
      }
    } catch {}
    finally { setLoading(false); }
  };

  const spendingTrend = transactions
    .filter(t => t.type === 'purchase')
    .slice(0, 7).reverse()
    .map(t => ({ day: new Date(t.created_at).toLocaleDateString('id-ID', { month: 'short', day: 'numeric' }), amount: t.amount }));

  const dailyUsedPct = wallet ? Math.min((wallet.daily_spent / (wallet.daily_limit || 1)) * 100, 100) : 0;

  const now = new Date();
  const greeting = now.getHours() < 12 ? 'Selamat Pagi' : now.getHours() < 17 ? 'Selamat Siang' : 'Selamat Sore';

  if (loading) return (
    <div className="p-6 flex justify-center items-center h-64">
      <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary" />
    </div>
  );

  return (
    <ProtectedRoute allowedRoles={['student']}>
      <div className="p-4 lg:p-6 space-y-5 max-w-4xl mx-auto">

        {/* Greeting */}
        <motion.div initial={{ opacity: 0, y: 16 }} animate={{ opacity: 1, y: 0 }}
          className="rounded-2xl p-6 text-white"
          style={{ background: `linear-gradient(135deg, ${(globalThis as any).__branding?.primary_color || '#56308C'}, #1e3a5f)` }}>
          <h1 className="text-xl font-bold">{greeting}, {user?.name?.split(' ')[0]}! 👋</h1>
          <p className="text-white/70 text-sm mt-1">
            {now.toLocaleDateString('id-ID', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}
          </p>
          {kpi && (
            <div className="mt-4 flex items-center gap-4">
              <div className="bg-white/20 rounded-xl px-4 py-2">
                <p className="text-xs text-white/70">Skor KPI</p>
                <p className="text-xl font-bold">{Number(kpi.score).toFixed(1)}</p>
              </div>
              <div className="bg-white/20 rounded-xl px-4 py-2">
                <p className="text-xs text-white/70">Peringkat</p>
                <p className="text-xl font-bold">#{kpi.rank}</p>
              </div>
            </div>
          )}
        </motion.div>

        {/* Quick stats */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          {[
            { label: 'Saldo E-Wallet', value: formatMoney(wallet?.balance || 0), icon: <FiDollarSign />, color: 'text-green-600', bg: 'bg-green-50', action: () => router.push(lp('/student/canteen')) },
            { label: 'Kehadiran', value: `${attendance?.attendance_rate || 0}%`, icon: <FiCalendar />, color: 'text-blue-600', bg: 'bg-blue-50', action: () => router.push(lp('/student/attendance')) },
            { label: 'Hadir Bulan Ini', value: `${attendance?.present || 0}/${attendance?.total || 0}`, icon: <FiCheckCircle />, color: 'text-purple-600', bg: 'bg-purple-50', action: null },
            { label: 'Terlambat', value: attendance?.late || 0, icon: <FiClock />, color: 'text-amber-600', bg: 'bg-amber-50', action: null },
          ].map((s, i) => (
            <motion.div key={i} initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.05 }}
              onClick={s.action || undefined}
              className={`${s.bg} rounded-xl p-4 ${s.action ? 'cursor-pointer hover:opacity-80' : ''}`}>
              <div className={`${s.color} mb-2`}>{s.icon}</div>
              <p className={`text-xl font-bold ${s.color}`}>{s.value}</p>
              <p className="text-xs text-gray-600 mt-0.5">{s.label}</p>
            </motion.div>
          ))}
        </div>

        {/* E-Wallet card */}
        {wallet && (
          <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}
            className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
            <div className="flex items-center justify-between mb-4">
              <h2 className="font-semibold text-gray-900">E-Wallet</h2>
              <button onClick={() => router.push(lp('/student/canteen'))}
                className="text-xs text-primary hover:underline">Lihat Semua</button>
            </div>
            <div className="flex items-center justify-between mb-4">
              <div>
                <p className="text-xs text-gray-500">Saldo</p>
                <p className="text-2xl font-bold text-gray-900">{formatMoney(wallet.balance)}</p>
              </div>
              <div className="text-right">
                <p className="text-xs text-gray-500">Terpakai Hari Ini</p>
                <p className="text-lg font-semibold text-red-500">{formatMoney(wallet.daily_spent)}</p>
                <p className="text-xs text-gray-400">dari {formatMoney(wallet.daily_limit)}</p>
              </div>
            </div>
            {/* Daily limit bar */}
            <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
              <div
                className={`h-full rounded-full transition-all ${dailyUsedPct > 80 ? 'bg-red-500' : dailyUsedPct > 50 ? 'bg-amber-500' : 'bg-green-500'}`}
                style={{ width: `${dailyUsedPct}%` }}
              />
            </div>
            <p className="text-xs text-gray-400 mt-1">{dailyUsedPct.toFixed(0)}% dari batas harian</p>
          </motion.div>
        )}

        {/* Spending trend */}
        {spendingTrend.length > 0 && (
          <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.3 }}
            className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
            <h2 className="font-semibold text-gray-900 mb-4">Tren Pengeluaran</h2>
            <ResponsiveContainer width="100%" height={140}>
              <LineChart data={spendingTrend}>
                <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                <XAxis dataKey="day" tick={{ fontSize: 10 }} />
                <YAxis tickFormatter={(v) => `${(v / 1000).toFixed(0)}k`} tick={{ fontSize: 10 }} />
                <Tooltip formatter={(v: any) => formatMoney(v)} />
                <Line type="monotone" dataKey="amount" stroke="#56308C" strokeWidth={2} dot={{ r: 3 }} />
              </LineChart>
            </ResponsiveContainer>
          </motion.div>
        )}

        {/* Grades */}
        {grades.length > 0 && (
          <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.4 }}
            className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
            <div className="flex items-center justify-between mb-4">
              <h2 className="font-semibold text-gray-900 flex items-center gap-2"><FiBook size={16} />Nilai Terkini</h2>
            </div>
            <div className="space-y-2">
              {grades.map((g, i) => (
                <div key={i} className="flex items-center justify-between py-2 border-b border-gray-50 last:border-0">
                  <p className="text-sm text-gray-700">{g.subject?.name}</p>
                  <div className="flex items-center gap-2">
                    {g.final_grade !== null && (
                      <span className="text-sm font-semibold text-gray-900">{Number(g.final_grade).toFixed(1)}</span>
                    )}
                    {g.grade_letter && (
                      <span className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold text-white ${
                        g.grade_letter === 'A' ? 'bg-green-500' :
                        g.grade_letter === 'B' ? 'bg-blue-500' :
                        g.grade_letter === 'C' ? 'bg-amber-500' : 'bg-red-500'
                      }`}>{g.grade_letter}</span>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </motion.div>
        )}

        {/* Recent transactions */}
        {transactions.length > 0 && (
          <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.5 }}
            className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
            <h2 className="font-semibold text-gray-900 mb-4">Transaksi Terbaru</h2>
            <div className="space-y-3">
              {transactions.slice(0, 5).map((tx) => (
                <div key={tx.id} className="flex items-center gap-3">
                  <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
                    tx.type === 'topup' ? 'bg-green-100' : tx.type === 'purchase' ? 'bg-red-100' : 'bg-blue-100'
                  }`}>
                    {tx.type === 'topup' ? <FiArrowDown className="text-green-600" size={14} /> :
                     tx.type === 'purchase' ? <FiShoppingCart className="text-red-600" size={14} /> :
                     <FiArrowUp className="text-blue-600" size={14} />}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm text-gray-900 truncate">{tx.description}</p>
                    <p className="text-xs text-gray-400">{new Date(tx.created_at).toLocaleDateString('id-ID')}</p>
                  </div>
                  <p className={`text-sm font-semibold flex-shrink-0 ${tx.type === 'topup' ? 'text-green-600' : 'text-red-600'}`}>
                    {tx.type === 'topup' ? '+' : '-'}{formatMoney(tx.amount)}
                  </p>
                </div>
              ))}
            </div>
          </motion.div>
        )}
      </div>
    </ProtectedRoute>
  );
}
