"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { AppShell } from "@/components/layout/AppShell";
import { Button, Card, CardContent } from "@/components/ui/index";
import { useLanguage } from "@/i18n/LanguageContext";
import { useAuth } from "@/hooks/useAuth";
import { hasPermission } from "@/lib/permissions";
import { toast } from "sonner";

export default function GoalDetailsPage() {
  const router = useRouter();
  const params = useParams<{ id: string }>();
  const { user } = useAuth();
  const { language } = useLanguage();
  const isArabic = language === "ar";
  const canRead = !!user && hasPermission(user.role, "goals:read");

  const [item, setItem] = useState<any | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!canRead || !params?.id) return;
    let cancelled = false;
    setLoading(true);
    fetch(`/api/goals/${params.id}`)
      .then(async (r) => {
        const json = await r.json();
        if (!r.ok) throw new Error(json.error ?? "Failed");
        return json.data;
      })
      .then((data) => {
        if (!cancelled) setItem(data);
      })
      .catch((e: any) => !cancelled && toast.error(e.message))
      .finally(() => !cancelled && setLoading(false));
    return () => {
      cancelled = true;
    };
  }, [canRead, params?.id]);

  const progress = item
    ? Math.max(0, Math.min(100, Math.round((Number(item.achievedValue || 0) / Math.max(1, Number(item.targetValue || 0))) * 100)))
    : 0;

  return (
    <AppShell
      breadcrumbs={[
        { label: isArabic ? "الأهداف" : "Goals", href: "/utilities/goals" },
        { label: isArabic ? "التفاصيل" : "Details" },
      ]}
    >
      {!canRead ? (
        <Card>
          <CardContent className="py-10 text-center text-muted-foreground">
            {isArabic ? "ليس لديك صلاحية عرض الأهداف." : "You do not have permission to view goals."}
          </CardContent>
        </Card>
      ) : loading ? (
        <Card><CardContent className="py-10 text-center text-muted-foreground">{isArabic ? "جاري التحميل..." : "Loading..."}</CardContent></Card>
      ) : !item ? (
        <Card><CardContent className="py-10 text-center text-muted-foreground">{isArabic ? "الهدف غير موجود" : "Goal not found"}</CardContent></Card>
      ) : (
        <div className="space-y-4">
          <div className="flex items-center justify-between gap-2">
            <h1 className="text-xl font-bold">{item.subject}</h1>
            <div className="flex gap-2">
              <Button variant="outline" onClick={() => router.push("/utilities/goals")}>{isArabic ? "رجوع" : "Back"}</Button>
            </div>
          </div>
          <Card>
            <CardContent className="py-5 grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
              <div><span className="text-muted-foreground">{isArabic ? "نوع الهدف: " : "Goal Type: "}</span>{item.goalType}</div>
              <div><span className="text-muted-foreground">{isArabic ? "المكلف: " : "Assignee: "}</span>{item.assigneeName || "—"}</div>
              <div><span className="text-muted-foreground">{isArabic ? "منجز: " : "Achieved: "}</span>{item.achievedValue}</div>
              <div><span className="text-muted-foreground">{isArabic ? "مستهدف: " : "Target: "}</span>{item.targetValue}</div>
              <div><span className="text-muted-foreground">{isArabic ? "من: " : "Start: "}</span>{String(item.startDate || "").slice(0, 10) || "—"}</div>
              <div><span className="text-muted-foreground">{isArabic ? "إلى: " : "End: "}</span>{String(item.endDate || "").slice(0, 10) || "—"}</div>
              <div className="sm:col-span-2">
                <span className="text-muted-foreground">{isArabic ? "نسبة الإنجاز: " : "Progress: "}</span>
                {progress}%
              </div>
            </CardContent>
          </Card>
        </div>
      )}
    </AppShell>
  );
}

