"use client";

import { useState, useEffect, FormEvent } from "react";
import { useAuth } from "@/lib/AuthContext";
import { useRouter } from "next/navigation";
import Link from "next/link";
import {
  ArrowLeft,
  Calculator,
  Hand,
  Clock,
  Check,
  Loader2,
  Info,
  TrendingUp,
  Landmark,
} from "lucide-react";
import ErrorFeedback from "@/components/ErrorFeedback";

interface ZakatStatus {
  totalPaid: number;
  remainingObligation: number;
  nisabThreshold: number;
}

interface ZakatAgent {
  id: string;
  name: string;
  country: string;
}

interface ZakatPayment {
  id: string;
  amount: number;
  agentName?: string;
  status: string;
  createdAt: string;
}

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

  // Status
  const [status, setStatus] = useState<ZakatStatus | null>(null);
  const [statusLoading, setStatusLoading] = useState(true);
  const [statusError, setStatusError] = useState<string | null>(null);

  // Calculator
  const [savings, setSavings] = useState("");
  const [calcResult, setCalcResult] = useState<number | null>(null);
  const [calcNisab, setCalcNisab] = useState<number | null>(null);
  const [calcLoading, setCalcLoading] = useState(false);
  const [calcError, setCalcError] = useState<string | null>(null);

  // Pay
  const [payAmount, setPayAmount] = useState("");
  const [agents, setAgents] = useState<ZakatAgent[]>([]);
  const [selectedAgent, setSelectedAgent] = useState("");
  const [payLoading, setPayLoading] = useState(false);
  const [payMessage, setPayMessage] = useState<{
    type: "success" | "error";
    text: string;
  } | null>(null);

  // History
  const [history, setHistory] = useState<ZakatPayment[]>([]);
  const [historyLoading, setHistoryLoading] = useState(true);
  const [historyError, setHistoryError] = useState<string | null>(null);

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

  useEffect(() => {
    if (token) {
      fetchStatus();
      fetchHistory();
      fetchAgents();
    }
  }, [token]);

  const fetchStatus = async () => {
    setStatusLoading(true);
    setStatusError(null);
    try {
      const res = await fetch("/mobile/api/flh/zakat/calculate", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ amount: 0 }),
      });
      if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || "Failed to fetch status");
      }
      const data = await res.json();
      setStatus({
        totalPaid: data.totalPaid ?? 0,
        remainingObligation: data.remainingObligation ?? 0,
        nisabThreshold: data.nisabThreshold ?? 2613,
      });
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Something went wrong";
      setStatusError(msg);
      // Set defaults so the UI works
      setStatus({ totalPaid: 0, remainingObligation: 0, nisabThreshold: 2613 });
    } finally {
      setStatusLoading(false);
    }
  };

  const fetchAgents = async () => {
    try {
      const res = await fetch("/mobile/api/flh/zakat/agents?country=MY");
      if (res.ok) {
        const data = await res.json();
        setAgents(Array.isArray(data) ? data : data.agents ?? []);
      }
    } catch {
      // silently fail
    }
  };

  const fetchHistory = async () => {
    setHistoryLoading(true);
    setHistoryError(null);
    try {
      const res = await fetch("/mobile/api/flh/zakat/history", {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || "Failed to fetch history");
      }
      const data = await res.json();
      setHistory(Array.isArray(data) ? data : data.payments ?? []);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Something went wrong";
      setHistoryError(msg);
    } finally {
      setHistoryLoading(false);
    }
  };

  const handleCalculate = async (e: FormEvent) => {
    e.preventDefault();
    const amount = parseFloat(savings);
    if (isNaN(amount) || amount <= 0) {
      setCalcError("Please enter a valid savings amount");
      return;
    }
    setCalcLoading(true);
    setCalcError(null);
    try {
      const res = await fetch("/mobile/api/flh/zakat/calculate", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ amount }),
      });
      if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || "Calculation failed");
      }
      const data = await res.json();
      setCalcResult(data.zakatAmount ?? amount * 0.025);
      setCalcNisab(data.nisabThreshold ?? null);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Calculation failed";
      setCalcError(msg);
    } finally {
      setCalcLoading(false);
    }
  };

  const handlePay = async (e: FormEvent) => {
    e.preventDefault();
    const amount = parseFloat(payAmount);
    if (isNaN(amount) || amount <= 0) {
      setPayMessage({ type: "error", text: "Please enter a valid amount" });
      return;
    }
    setPayLoading(true);
    setPayMessage(null);
    try {
      const res = await fetch("/mobile/api/flh/zakat/pay", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          amount,
          agentId: selectedAgent || undefined,
          idempotencyKey: `${Date.now()}-${Math.random().toString(36).slice(2)}`,
        }),
      });
      if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || "Payment failed");
      }
      setPayMessage({ type: "success", text: "Zakat payment successful!" });
      setPayAmount("");
      fetchHistory();
      fetchStatus();
      setTimeout(() => setPayMessage(null), 4000);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Payment failed";
      setPayMessage({ type: "error", text: msg });
      setTimeout(() => setPayMessage(null), 4000);
    } finally {
      setPayLoading(false);
    }
  };

  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;

  const nisabDisplay = calcNisab ?? status?.nisabThreshold ?? 2613;

  return (
    <div className="min-h-dvh bg-[#0a0a0f] pb-24">
      {/* Header */}
      <div className="px-4 pt-6 pb-2 flex items-center gap-3">
        <Link
          href="/flh"
          className="w-8 h-8 rounded-full bg-gray-800/60 flex items-center justify-center active:scale-90 transition"
        >
          <ArrowLeft size={16} className="text-gray-500" />
        </Link>
        <div>
          <h1 className="text-xl font-bold text-white">Zakat</h1>
          <p className="text-xs text-gray-500">Purify your wealth</p>
        </div>
      </div>

      <div className="px-4 space-y-5 animate-fade-in">
        {/* a) Overview Card */}
        <div className="bg-gradient-to-br from-amber-900/20 to-[#0a0a0f] border border-amber-800/30 rounded-2xl p-5">
          <h2 className="text-sm font-semibold text-amber-300 mb-3 flex items-center gap-2">
            <Info size={16} />
            Your Zakat Summary
          </h2>
          {statusLoading ? (
            <div className="flex items-center justify-center py-4">
              <div className="w-6 h-6 rounded-full border-2 border-[#D4AF37]/30 border-t-[#D4AF37] animate-spin" />
            </div>
          ) : statusError ? (
            <ErrorFeedback
              error={statusError}
              kind="default"
              onRetry={fetchStatus}
              context="flh"
            />
          ) : (
            <div className="grid grid-cols-2 gap-3">
              <div className="bg-[#111118] border border-gray-800/60 rounded-xl p-3 text-center">
                <p className="text-xs text-gray-500 mb-1">Paid This Year</p>
                <p className="text-lg font-bold text-emerald-400">
                  {(status?.totalPaid ?? 0).toLocaleString()} FLH
                </p>
              </div>
              <div className="bg-[#111118] border border-gray-800/60 rounded-xl p-3 text-center">
                <p className="text-xs text-gray-500 mb-1">Remaining</p>
                <p className="text-lg font-bold text-amber-400">
                  {(status?.remainingObligation ?? 0).toLocaleString()} FLH
                </p>
              </div>
            </div>
          )}
        </div>

        {/* b) Zakat Calculator */}
        <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5">
          <h2 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
            <Calculator size={16} className="text-amber-400" />
            Zakat Calculator
          </h2>
          <form onSubmit={handleCalculate} className="space-y-3">
            <div>
              <label className="text-xs text-gray-500 mb-1.5 block">
                Total Savings (FLH)
              </label>
              <input
                type="number"
                min={0}
                step={1}
                value={savings}
                onChange={(e) => setSavings(e.target.value)}
                placeholder="e.g. 100000"
                className="w-full bg-[#1a1a24] border border-gray-800/60 rounded-xl px-4 py-4 text-white placeholder-gray-600 focus:outline-none focus:border-amber-800/50 focus:ring-1 focus:ring-amber-800/30 transition"
              />
            </div>
            <button
              type="submit"
              disabled={calcLoading}
              className="w-full px-4 py-4 rounded-xl bg-amber-600 text-white font-semibold text-sm disabled:opacity-50 active:opacity-80 transition flex items-center justify-center gap-2"
            >
              {calcLoading ? (
                <Loader2 size={16} className="animate-spin" />
              ) : (
                <>
                  <Calculator size={16} />
                  Calculate
                </>
              )}
            </button>
          </form>
          {calcError && (
            <ErrorFeedback
              error={calcError}
              kind="default"
              onRetry={() => setCalcError(null)}
              context="flh"
            />
          )}
          {calcResult !== null && (
            <div className="mt-4 bg-amber-900/10 border border-amber-800/30 rounded-xl p-4">
              <p className="text-xs text-amber-300/70 mb-1">
                Your Zakat Obligation (2.5%)
              </p>
              <p className="text-2xl font-bold text-amber-400">
                {calcResult.toLocaleString()} FLH
              </p>
              <p className="text-xs text-gray-500 mt-2">
                Nisab threshold: {nisabDisplay.toLocaleString()} FLH — zakat is
                due if your savings exceed this amount and have been held for
                one lunar year.
              </p>
            </div>
          )}
        </div>

        {/* c) Pay Zakat */}
        <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5">
          <h2 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
            <Hand size={16} className="text-amber-400" />
            Pay Zakat
          </h2>
          <form onSubmit={handlePay} className="space-y-3">
            <div>
              <label className="text-xs text-gray-500 mb-1.5 block">
                Amount (FLH)
              </label>
              <input
                type="number"
                min={1}
                step={1}
                value={payAmount}
                onChange={(e) => setPayAmount(e.target.value)}
                placeholder="Enter amount"
                className="w-full bg-[#1a1a24] border border-gray-800/60 rounded-xl px-4 py-4 text-white placeholder-gray-600 focus:outline-none focus:border-amber-800/50 focus:ring-1 focus:ring-amber-800/30 transition"
              />
            </div>
            {agents.length > 0 && (
              <div>
                <label className="text-xs text-gray-500 mb-1.5 block">
                  Zakat Agent (optional)
                </label>
                <select
                  value={selectedAgent}
                  onChange={(e) => setSelectedAgent(e.target.value)}
                  className="w-full bg-[#1a1a24] border border-gray-800/60 rounded-xl px-4 py-4 text-white focus:outline-none focus:border-amber-800/50 transition"
                >
                  <option value="">General Zakat Fund</option>
                  {agents.map((agent) => (
                    <option key={agent.id} value={agent.id}>
                      {agent.name}
                    </option>
                  ))}
                </select>
              </div>
            )}
            <button
              type="submit"
              disabled={payLoading}
              className="w-full px-4 py-4 rounded-xl bg-[#D4AF37] text-[#0a0a0f] font-semibold text-sm disabled:opacity-50 active:opacity-80 transition flex items-center justify-center gap-2"
            >
              {payLoading ? (
                <Loader2 size={16} className="animate-spin" />
              ) : (
                <>
                  <Hand size={16} />
                  Pay Zakat
                </>
              )}
            </button>
          </form>
          {payMessage && payMessage.type === "success" && (
            <div className="mt-3 flex items-center gap-2 p-3 rounded-xl text-sm bg-emerald-900/20 border border-emerald-800/40 text-emerald-400">
              <Check size={16} />
              {payMessage.text}
            </div>
          )}
          {payMessage && payMessage.type === "error" && (
            <ErrorFeedback
              error={payMessage.text}
              kind="default"
              onRetry={() => setPayMessage(null)}
              context="flh"
            />
          )}
        </div>

        {/* d) History */}
        <div>
          <h2 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
            <Clock size={16} className="text-gray-500" />
            Zakat History
          </h2>
          {historyLoading ? (
            <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-6 flex items-center justify-center">
              <div className="w-6 h-6 rounded-full border-2 border-[#D4AF37]/30 border-t-[#D4AF37] animate-spin" />
            </div>
          ) : historyError ? (
            <ErrorFeedback
              error={historyError}
              kind="default"
              onRetry={fetchHistory}
              context="flh"
            />
          ) : history.length === 0 ? (
            <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5 text-center">
              <TrendingUp size={20} className="mx-auto text-gray-700 mb-2" />
              <p className="text-sm text-gray-500">No zakat payments yet</p>
              <p className="text-xs text-gray-700 mt-1">
                Your zakat payments will appear here
              </p>
            </div>
          ) : (
            <div className="space-y-2">
              {history.map((payment) => (
                <div
                  key={payment.id}
                  className="bg-[#111118] border border-gray-800/60 rounded-xl px-4 py-3 flex items-center justify-between"
                >
                  <div className="flex items-center gap-3">
                    <div className="w-8 h-8 rounded-full bg-amber-900/20 flex items-center justify-center">
                      <Landmark size={14} className="text-amber-400" />
                    </div>
                    <div>
                      <p className="text-sm font-medium text-white">
                        {payment.amount.toLocaleString()} FLH
                      </p>
                      <p className="text-xs text-gray-500">
                        {payment.agentName ?? "General Zakat Fund"} —{" "}
                        {new Date(payment.createdAt).toLocaleDateString()}
                      </p>
                    </div>
                  </div>
                  <span
                    className={`text-xs font-medium capitalize ${
                      payment.status === "completed"
                        ? "text-emerald-400"
                        : payment.status === "pending"
                          ? "text-amber-400"
                          : "text-gray-500"
                    }`}
                  >
                    {payment.status}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>

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