"use client";

import { useCallback, useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { apiFetch, formatMoney, formatDateTime, gradeLabel } from "@/lib/client-utils";
import { DashboardData, SchoolSettingsDTO } from "@/lib/types";
import { useStructure } from "@/lib/structure-context";
import {
  Users, TrendingUp, TrendingDown, Scale, CircleAlert, Megaphone,
  ReceiptText, Wallet, Plus, Trash2, Loader2, CalendarClock, BellRing,
} from "lucide-react";
import {
  ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,
} from "recharts";

interface DashboardViewProps {
  settings: SchoolSettingsDTO | null;
  userRole: string;
  userName: string;
  refreshKey: number;
  onGoPayment: () => void;
  onGoStudents: () => void;
}

export default function DashboardView({ settings, userRole, userName, refreshKey, onGoPayment, onGoStudents }: DashboardViewProps) {
  const { toast } = useToast();
  const currency = settings?.currency || "د.ع";
  const isFinance = userRole === "ADMIN" || userRole === "ACCOUNTANT";
  const isAdmin = userRole === "ADMIN";
  const { customLabels } = useStructure();

  const [data, setData] = useState<DashboardData | null>(null);
  const [loading, setLoading] = useState(true);

  // نافذة إضافة تنبيه (مدير)
  const [announceOpen, setAnnounceOpen] = useState(false);
  const [announceMsg, setAnnounceMsg] = useState("");
  const [announceLevel, setAnnounceLevel] = useState("INFO");
  const [announceLoading, setAnnounceLoading] = useState(false);

  const loadDashboard = useCallback(async () => {
    setLoading(true);
    try {
      const d = await apiFetch<DashboardData>("/api/dashboard");
      setData(d);
    } catch (err) {
      toast({ title: "تعذر تحميل لوحة المعلومات", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setLoading(false);
    }
  }, [toast]);

  useEffect(() => {
    loadDashboard();
  }, [loadDashboard, refreshKey]);

  async function addAnnouncement() {
    if (announceMsg.trim().length < 3) {
      toast({ title: "نص التنبيه قصير جداً", variant: "destructive" });
      return;
    }
    setAnnounceLoading(true);
    try {
      await apiFetch("/api/announcements", {
        method: "POST",
        body: JSON.stringify({ message: announceMsg.trim(), level: announceLevel }),
      });
      toast({ title: "تم نشر التنبيه", description: "سيظهر لجميع مستخدمي النظام في لوحة المعلومات" });
      setAnnounceMsg("");
      setAnnounceOpen(false);
      loadDashboard();
    } catch (err) {
      toast({ title: "فشل نشر التنبيه", description: err instanceof Error ? err.message : "", variant: "destructive" });
    } finally {
      setAnnounceLoading(false);
    }
  }

  async function removeAnnouncement(id: string) {
    try {
      await apiFetch(`/api/announcements?id=${id}`, { method: "DELETE" });
      loadDashboard();
    } catch {
      toast({ title: "فشل حذف التنبيه", variant: "destructive" });
    }
  }

  if (loading && !data) {
    return (
      <div className="flex items-center justify-center py-24">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    );
  }

  const greeting = new Date().getHours() < 12 ? "صباح الخير" : new Date().getHours() < 17 ? "طاب يومك" : "مساء الخير";

  return (
    <div className="space-y-5">
      {/* ترحيب */}
      <div className="relative isolate flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 overflow-hidden rounded-2xl border border-primary/15 bg-gradient-to-br from-primary/10 via-card to-card p-4 sm:p-6 shadow-sm">
        <div aria-hidden className="absolute -left-12 -top-16 -z-10 h-48 w-48 rounded-full bg-primary/10 blur-2xl" />
        <div className="min-w-0">
          <p className="text-xs font-semibold tracking-wide text-primary">نظام الإدارة المدرسية</p>
          <h1 className="mt-1 text-xl sm:text-2xl font-extrabold leading-tight">{greeting}، {userName} 👋</h1>
          <p className="text-sm text-muted-foreground mt-2">
            إليك ملخص اليوم في {settings?.nameAr || "المدرسة"} — {new Intl.DateTimeFormat("ar-IQ-u-nu-latn", { dateStyle: "full" }).format(new Date())}
          </p>
        </div>
        {isAdmin && (
          <Button className="w-full sm:w-auto shrink-0" onClick={() => setAnnounceOpen(true)}>
            <Plus className="w-4 h-4 ml-2" />
            نشر تنبيه إداري
          </Button>
        )}
      </div>

      {/* الإجراءات السريعة — أعلى الصفحة */}
      <div className="grid gap-3 sm:grid-cols-3">
        <Button variant="outline" className="h-14 rounded-xl bg-card text-sm sm:text-base justify-start gap-3 shadow-sm transition-all hover:-translate-y-0.5 hover:shadow-md" onClick={onGoPayment}>
          <ReceiptText className="w-5 h-5 text-primary" />
          استلام قسط جديد
        </Button>
        <Button variant="outline" className="h-14 rounded-xl bg-card text-sm sm:text-base justify-start gap-3 shadow-sm transition-all hover:-translate-y-0.5 hover:shadow-md" onClick={onGoStudents}>
          <Users className="w-5 h-5 text-primary" />
          تسجيل طالب / بحث
        </Button>
        <Button variant="outline" className="h-14 rounded-xl bg-card text-sm sm:text-base justify-start gap-3 shadow-sm transition-all hover:-translate-y-0.5 hover:shadow-md" onClick={onGoStudents}>
          <CalendarClock className="w-5 h-5 text-primary" />
          متابعة المتأخرات
        </Button>
      </div>

      {/* تنبيهات الإدارة — بالأحمر للإداري والمحاسب لجذب الانتباه */}
      {data?.announcements && data.announcements.length > 0 && (
        <div className="space-y-2">
          {data.announcements.map((a) => {
            const redAlert = !isAdmin; // الإداري والمحاسب يرون كل التنبيهات بالأحمر
            const red = redAlert || a.level === "URGENT";
            const amber = !red && a.level === "WARNING";
            return (
              <div
                key={a.id}
                className={`flex items-start justify-between gap-3 rounded-xl border-2 p-3 ${
                  red
                    ? "border-red-400 bg-red-50 shadow-sm"
                    : amber
                      ? "border-amber-300 bg-amber-50"
                      : "border-primary/30 bg-primary/5"
                }`}
              >
                <div className="flex items-start gap-2 min-w-0">
                  <BellRing className={`w-5 h-5 shrink-0 mt-0.5 ${red ? "text-red-600" : amber ? "text-amber-600" : "text-primary"}`} />
                  <div className="min-w-0">
                    {red && (
                      <p className="text-[10px] font-extrabold text-red-700 mb-0.5">تنبيه إداري من المدير</p>
                    )}
                    <p className="text-sm font-medium">{a.message}</p>
                    <p className="text-[11px] text-muted-foreground mt-0.5">
                      {a.creator?.fullName ?? "الإدارة"} · {formatDateTime(a.createdAt)}
                    </p>
                  </div>
                </div>
                {isAdmin && (
                  <Button variant="ghost" size="icon" className="h-7 w-7 shrink-0" onClick={() => removeAnnouncement(a.id)} aria-label="إلغاء التنبيه">
                    <Trash2 className="w-4 h-4 text-destructive" />
                  </Button>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* الإحصائيات */}
      <div className={`grid gap-3 ${isFinance ? "sm:grid-cols-2 xl:grid-cols-4" : "sm:grid-cols-1 xl:grid-cols-2"}`}>
        <Card className="rounded-2xl shadow-sm transition-shadow hover:shadow-md">
          <CardContent className="pt-5 flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">عدد الطلبة النشطين</p>
              <p className="text-3xl font-extrabold mt-1">{data?.stats.studentsCount ?? 0}</p>
            </div>
            <div className="w-12 h-12 rounded-xl bg-primary/10 text-primary flex items-center justify-center">
              <Users className="w-6 h-6" />
            </div>
          </CardContent>
        </Card>
        {isFinance && (
          <>
            <Card className="rounded-2xl shadow-sm transition-shadow hover:shadow-md">
              <CardContent className="pt-5 flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">إيرادات هذا الشهر</p>
                  <p className="text-2xl font-extrabold text-emerald-700 mt-1">{formatMoney(data?.stats.monthIncome ?? 0, currency)}</p>
                  <p className="text-[11px] text-muted-foreground mt-1">اليوم: {formatMoney(data?.stats.todayIncome ?? 0, currency)}</p>
                </div>
                <div className="w-12 h-12 rounded-xl bg-emerald-100 text-emerald-700 flex items-center justify-center">
                  <TrendingUp className="w-6 h-6" />
                </div>
              </CardContent>
            </Card>
            <Card className="rounded-2xl shadow-sm transition-shadow hover:shadow-md">
              <CardContent className="pt-5 flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">مصروفات هذا الشهر</p>
                  <p className="text-2xl font-extrabold text-red-600 mt-1">{formatMoney(data?.stats.monthExpenses ?? 0, currency)}</p>
                  <p className="text-[11px] text-muted-foreground mt-1">الصافي العام: {formatMoney(data?.stats.netBalance ?? 0, currency)}</p>
                </div>
                <div className="w-12 h-12 rounded-xl bg-red-100 text-red-600 flex items-center justify-center">
                  <TrendingDown className="w-6 h-6" />
                </div>
              </CardContent>
            </Card>
            <Card className="rounded-2xl shadow-sm transition-shadow hover:shadow-md">
              <CardContent className="pt-5 flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">أقساط غير محصلة (متبقي الكل)</p>
                  <p className="text-2xl font-extrabold text-amber-600 mt-1">{formatMoney(data?.stats.outstanding ?? 0, currency)}</p>
                  <p className="text-[11px] text-muted-foreground mt-1">{data?.lateStudents.length ?? 0} طالب متأخر عن السداد</p>
                </div>
                <div className="w-12 h-12 rounded-xl bg-amber-100 text-amber-600 flex items-center justify-center">
                  <Scale className="w-6 h-6" />
                </div>
              </CardContent>
            </Card>
          </>
        )}
      </div>

      {/* أقساط متأخرة */}
      <Card className={data?.lateStudents.length ? "border-amber-300" : ""}>
        <CardHeader className="pb-3">
          <CardTitle className="text-lg flex items-center gap-2">
            <CircleAlert className="w-5 h-5 text-amber-600" />
            أقساط متأخرة — تحتاج متابعة
          </CardTitle>
          <CardDescription>طلبة تجاوزوا تاريخ الاستحقاق أو مضى فترة طويلة دون سداد كامل</CardDescription>
        </CardHeader>
        <CardContent>
          {!data || data.lateStudents.length === 0 ? (
            <p className="text-sm text-muted-foreground text-center py-6">ممتاز! لا توجد أقساط متأخرة حالياً</p>
          ) : (
            <div className="space-y-2 max-h-80 overflow-y-auto">
              {data.lateStudents.map((s) => (
                <div key={s.id} className="flex items-center justify-between gap-3 rounded-xl border border-amber-200 bg-amber-50/60 p-3">
                  <div className="min-w-0">
                    <p className="font-semibold text-sm truncate">{s.nameAr}</p>
                    <p className="text-[11px] text-muted-foreground" dir="ltr">
                      {s.studentCode} · {gradeLabel(s.grade, customLabels)}
                      {s.feeDueDate ? ` · استحقاق: ${formatDateTime(s.feeDueDate).split("،")[0]}` : ""}
                    </p>
                  </div>
                  <div className="flex items-center gap-2 shrink-0">
                    <Badge variant="destructive">{formatMoney(s.remaining, currency)}</Badge>
                    {isFinance && (
                      <Button size="sm" variant="outline" onClick={onGoPayment}>
                        استلام
                      </Button>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      <div className={`grid gap-4 ${isFinance ? "lg:grid-cols-2" : ""}`}>
        {/* رسم بياني */}
        {isFinance && data?.monthlyChart && data.monthlyChart.length > 0 && (
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-lg flex items-center gap-2">
                <Wallet className="w-5 h-5 text-primary" />
                الإيرادات والمصروفات هذا العام
              </CardTitle>
              <CardDescription>مقارنة شهرية لحركة الميزانية</CardDescription>
            </CardHeader>
            <CardContent>
              <div style={{ width: "100%", height: 260 }} dir="ltr">
                <ResponsiveContainer width="100%" height="100%">
                  <AreaChart data={data.monthlyChart} margin={{ top: 5, right: 10, left: 10, bottom: 5 }}>
                    <defs>
                      <linearGradient id="gIncome" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor="#059669" stopOpacity={0.35} />
                        <stop offset="95%" stopColor="#059669" stopOpacity={0} />
                      </linearGradient>
                      <linearGradient id="gExp" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor="#ef4444" stopOpacity={0.3} />
                        <stop offset="95%" stopColor="#ef4444" stopOpacity={0} />
                      </linearGradient>
                    </defs>
                    <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                    <XAxis dataKey="month" tick={{ fontSize: 11, fontFamily: "Cairo" }} />
                    <YAxis tick={{ fontSize: 10 }} tickFormatter={(v: number) => (v >= 1000 ? `${Math.round(v / 1000)}k` : String(v))} />
                    <Tooltip
                      formatter={(value: number | string) => formatMoney(Number(value), currency)}
                      labelStyle={{ fontFamily: "Cairo" }}
                      contentStyle={{ fontFamily: "Cairo", direction: "rtl", borderRadius: 12 }}
                    />
                    <Area type="monotone" dataKey="income" name="الإيرادات" stroke="#059669" fill="url(#gIncome)" strokeWidth={2} />
                    <Area type="monotone" dataKey="expenses" name="المصروفات" stroke="#ef4444" fill="url(#gExp)" strokeWidth={2} />
                  </AreaChart>
                </ResponsiveContainer>
              </div>
            </CardContent>
          </Card>
        )}

        {/* آخر العمليات */}
        {isFinance && (
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-lg flex items-center gap-2">
                <ReceiptText className="w-5 h-5 text-primary" />
                آخر العمليات المالية
              </CardTitle>
              <CardDescription>أحدث الأقساط المستلمة والمصروفات المسجلة</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-2 max-h-72 overflow-y-auto">
                {data?.recentPayments.map((p) => (
                  <div key={p.id} className="flex items-center justify-between rounded-lg border px-3 py-2 text-sm">
                    <div className="min-w-0">
                      <p className="font-medium truncate">{p.student?.nameAr} — وصل #{p.receiptNumber}</p>
                      <p className="text-[11px] text-muted-foreground">{formatDateTime(p.paidAt)} · بواسطة {p.creator?.fullName}</p>
                    </div>
                    <span className="font-bold text-emerald-700 shrink-0">+{formatMoney(p.amount, currency)}</span>
                  </div>
                ))}
                {data?.recentExpenses.map((e) => (
                  <div key={e.id} className="flex items-center justify-between rounded-lg border px-3 py-2 text-sm">
                    <div className="min-w-0">
                      <p className="font-medium truncate">{e.description}</p>
                      <p className="text-[11px] text-muted-foreground">{formatDateTime(e.spentAt)} · {e.category}</p>
                    </div>
                    <span className="font-bold text-red-600 shrink-0">-{formatMoney(e.amount, currency)}</span>
                  </div>
                ))}
                {data && data.recentPayments.length === 0 && data.recentExpenses.length === 0 && (
                  <p className="text-sm text-muted-foreground text-center py-6">لا توجد عمليات بعد</p>
                )}
              </div>
            </CardContent>
          </Card>
        )}
      </div>

      {/* نافذة نشر تنبيه */}
      <Dialog open={announceOpen} onOpenChange={setAnnounceOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Megaphone className="w-5 h-5 text-primary" />
              نشر تنبيه إداري
            </DialogTitle>
            <DialogDescription>سيظهر التنبيه في لوحة معلومات جميع المستخدمين</DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            <div className="space-y-2">
              <Label htmlFor="ann-msg">نص التنبيه</Label>
              <Input
                id="ann-msg"
                value={announceMsg}
                onChange={(e) => setAnnounceMsg(e.target.value)}
                placeholder="مثال: اجتماع أولياء أمور الصف السادس يوم الخميس"
              />
            </div>
            <div className="space-y-2">
              <Label>مستوى الأهمية</Label>
              <Select value={announceLevel} onValueChange={setAnnounceLevel}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="INFO">عادي</SelectItem>
                  <SelectItem value="WARNING">هام</SelectItem>
                  <SelectItem value="URGENT">عاجل</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <Button className="w-full" onClick={addAnnouncement} disabled={announceLoading}>
              {announceLoading ? <Loader2 className="w-4 h-4 ml-2 animate-spin" /> : <Megaphone className="w-4 h-4 ml-2" />}
              نشر التنبيه
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
