"use client";

import { useState, useEffect } from "react";
import { useAuth } from "@/lib/AuthContext";
import { useRouter } from "next/navigation";
import Link from "next/link";
import {
  Heart,
  Gift,
  Hand,
  Building2,
  Calculator,
  Info,
  ArrowRight,
  Sparkles,
} from "lucide-react";
import ErrorFeedback from "@/components/ErrorFeedback";

interface SummaryData {
  zakatTotal: number;
  sadaqahTotal: number;
  hibahTotal: number;
  waqfTotal: number;
}

const PILLARS = [
  {
    slug: "zakat",
    name: "Zakat",
    desc: "Obligatory charity — purify your wealth",
    icon: Calculator,
    color: "text-amber-400",
    bg: "bg-amber-900/20",
  },
  {
    slug: "sadaqah",
    name: "Sadaqah",
    desc: "Voluntary charity for the sake of Allah",
    icon: Gift,
    color: "text-emerald-400",
    bg: "bg-emerald-900/20",
  },
  {
    slug: "hibah",
    name: "Hibah",
    desc: "Give gifts to loved ones",
    icon: Heart,
    color: "text-rose-400",
    bg: "bg-rose-900/20",
  },
  {
    slug: "waqf",
    name: "Waqf",
    desc: "Endowment for perpetual rewards",
    icon: Building2,
    color: "text-sky-400",
    bg: "bg-sky-900/20",
  },
];

export default function FlhDashboard() {
  const { user, token, loading: authLoading } = useAuth();
  const router = useRouter();

  const [summary, setSummary] = useState<SummaryData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!authLoading && !token) router.push("/auth");
  }, [authLoading, token, router]);

  useEffect(() => {
    if (token) fetchSummary();
  }, [token]);

  const fetchSummary = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/mobile/api/flh/summary", {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || "Failed to load summary");
      }
      const data = await res.json();
      setSummary(data);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Something went wrong";
      setError(msg);
    } finally {
      setLoading(false);
    }
  };

  const getPillarTotal = (slug: string): number => {
    if (!summary) return 0;
    switch (slug) {
      case "zakat":
        return summary.zakatTotal ?? 0;
      case "sadaqah":
        return summary.sadaqahTotal ?? 0;
      case "hibah":
        return summary.hibahTotal ?? 0;
      case "waqf":
        return summary.waqfTotal ?? 0;
      default:
        return 0;
    }
  };

  if (authLoading) {
    return (
      <div className="min-h-dvh bg-[#0a0a0f] flex items-center justify-center">
        <div className="w-8 h-8 rounded-full border-2 border-[#D4AF37]/30 border-t-[#D4AF37] animate-spin" />
      </div>
    );
  }

  if (!user) return null;

  return (
    <div className="min-h-dvh bg-[#0a0a0f] pb-24">
      <div className="px-4 pt-6 pb-2">
        <h1 className="text-xl font-bold text-white">Islamic Finance</h1>
        <p className="text-sm text-gray-500 mt-1">
          Zakat · Sadaqah · Hibah · Waqf
        </p>
      </div>

      <div className="px-4 space-y-5 animate-fade-in">
        {error && (
          <ErrorFeedback
            error={error}
            kind="default"
            onRetry={fetchSummary}
            context="flh"
          />
        )}

        {loading ? (
          <div className="flex items-center justify-center py-12">
            <div className="w-8 h-8 rounded-full border-2 border-[#D4AF37]/30 border-t-[#D4AF37] animate-spin" />
          </div>
        ) : (
          <>
            {/* Pillar Cards Grid */}
            <div className="grid grid-cols-2 gap-3">
              {PILLARS.map((pillar) => (
                <Link
                  key={pillar.slug}
                  href={`/flh/${pillar.slug}`}
                  className="bg-[#111118] border border-gray-800/60 rounded-2xl p-4 active:scale-[0.97] transition-all hover:border-gray-700/60 flex flex-col"
                >
                  <div
                    className={`w-10 h-10 rounded-xl ${pillar.bg} flex items-center justify-center mb-3`}
                  >
                    <pillar.icon size={20} className={pillar.color} />
                  </div>
                  <h3 className="text-sm font-semibold text-white mb-1">
                    {pillar.name}
                  </h3>
                  <p className="text-xs text-gray-500 leading-relaxed mb-3 flex-1">
                    {pillar.desc}
                  </p>
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-gray-600">Total</span>
                    <span className="text-xs font-semibold text-[#D4AF37]">
                      {getPillarTotal(pillar.slug).toLocaleString()} FLH
                    </span>
                  </div>
                </Link>
              ))}
            </div>

            {/* Quick Actions */}
            <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5">
              <h3 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
                <Sparkles size={16} className="text-[#D4AF37]" />
                Quick Actions
              </h3>
              <Link
                href="/flh/zakat"
                className="flex items-center justify-between bg-[#1a1a24] border border-gray-800/60 rounded-xl px-4 py-3 active:scale-[0.98] transition"
              >
                <div className="flex items-center gap-3">
                  <div className="w-8 h-8 rounded-lg bg-amber-900/20 flex items-center justify-center">
                    <Calculator size={16} className="text-amber-400" />
                  </div>
                  <span className="text-sm text-gray-300 font-medium">
                    Calculate Zakat
                  </span>
                </div>
                <ArrowRight size={16} className="text-gray-600" />
              </Link>
            </div>

            {/* Educational Snippet */}
            <div className="bg-gradient-to-br from-[#D4AF37]/20 to-[#0a0a0f] border border-[#D4AF37]/30 rounded-2xl p-5">
              <div className="flex items-start gap-3">
                <Info size={18} className="text-[#D4AF37] mt-0.5 shrink-0" />
                <div>
                  <h3 className="text-sm font-semibold text-[#D4AF37] mb-1">
                    Islamic Finance in Islam
                  </h3>
                  <p className="text-xs text-gray-400 leading-relaxed">
                    Islamic finance is guided by Shariah principles that promote
                    justice, transparency, and social welfare. Zakat purifies
                    wealth, Sadaqah spreads blessings, Hibah strengthens family
                    bonds, and Waqf creates perpetual charity. Each act of
                    giving brings barakah and draws us closer to Allah.
                  </p>
                </div>
              </div>
            </div>

            <div className="h-4" />
          </>
        )}
      </div>
    </div>
  );
}
