"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,
  Building2,
  Clock,
  Check,
  Loader2,
  TrendingUp,
  Hand,
  Landmark,
} from "lucide-react";
import ErrorFeedback from "@/components/ErrorFeedback";

interface WaqfPool {
  id: string;
  name: string;
  beneficiary: string;
  totalPrincipal: number;
  availableYield: number;
}

interface Contribution {
  id: string;
  poolId: string;
  poolName?: string;
  amount: number;
  createdAt: string;
}

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

  // Pools
  const [pools, setPools] = useState<WaqfPool[]>([]);
  const [poolsLoading, setPoolsLoading] = useState(true);
  const [poolsError, setPoolsError] = useState<string | null>(null);

  // My Contributions
  const [contributions, setContributions] = useState<Contribution[]>([]);
  const [contribLoading, setContribLoading] = useState(true);
  const [contribError, setContribError] = useState<string | null>(null);

  // Contribute
  const [selectedPoolId, setSelectedPoolId] = useState("");
  const [contributeAmount, setContributeAmount] = useState("");
  const [contributeLoading, setContributeLoading] = useState(false);
  const [contributeMessage, setContributeMessage] = useState<{
    type: "success" | "error";
    text: string;
  } | null>(null);

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

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

  const fetchPools = async () => {
    setPoolsLoading(true);
    setPoolsError(null);
    try {
      const res = await fetch("/mobile/api/flh/waqf/pools");
      if (!res.ok) throw new Error("Failed to fetch waqf pools");
      const data = await res.json();
      setPools(Array.isArray(data) ? data : data.pools ?? []);
      if (Array.isArray(data) && data.length > 0) {
        setSelectedPoolId(data[0].id);
      } else if (data.pools?.length > 0) {
        setSelectedPoolId(data.pools[0].id);
      }
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Something went wrong";
      setPoolsError(msg);
    } finally {
      setPoolsLoading(false);
    }
  };

  const fetchContributions = async () => {
    setContribLoading(true);
    setContribError(null);
    try {
      const res = await fetch("/mobile/api/flh/waqf/my-contributions", {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (!res.ok) throw new Error("Failed to fetch contributions");
      const data = await res.json();
      setContributions(
        Array.isArray(data) ? data : data.contributions ?? []
      );
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Something went wrong";
      setContribError(msg);
    } finally {
      setContribLoading(false);
    }
  };

  const handleContribute = async (e: FormEvent) => {
    e.preventDefault();
    const amount = parseFloat(contributeAmount);
    if (isNaN(amount) || amount <= 0) {
      setContributeMessage({
        type: "error",
        text: "Please enter a valid amount",
      });
      return;
    }
    if (!selectedPoolId) {
      setContributeMessage({
        type: "error",
        text: "Please select a pool",
      });
      return;
    }
    setContributeLoading(true);
    setContributeMessage(null);
    try {
      const res = await fetch("/mobile/api/flh/waqf/contribute", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          poolId: selectedPoolId,
          amount,
        }),
      });
      if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || "Contribution failed");
      }
      setContributeMessage({
        type: "success",
        text: `Contributed ${amount} FLH to waqf pool!`,
      });
      setContributeAmount("");
      fetchContributions();
      setTimeout(() => setContributeMessage(null), 4000);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Contribution failed";
      setContributeMessage({ type: "error", text: msg });
      setTimeout(() => setContributeMessage(null), 4000);
    } finally {
      setContributeLoading(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;

  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">Waqf</h1>
          <p className="text-xs text-gray-500">Endowment for perpetual rewards</p>
        </div>
      </div>

      <div className="px-4 space-y-5 animate-fade-in">
        {/* a) Pools Grid */}
        <div>
          <h2 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
            <Building2 size={16} className="text-sky-400" />
            Waqf Pools
          </h2>
          {poolsLoading ? (
            <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>
          ) : poolsError ? (
            <ErrorFeedback
              error={poolsError}
              kind="default"
              onRetry={fetchPools}
              context="flh"
            />
          ) : pools.length === 0 ? (
            <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5 text-center">
              <Building2 size={20} className="mx-auto text-gray-700 mb-2" />
              <p className="text-sm text-gray-500">No waqf pools available</p>
              <p className="text-xs text-gray-700 mt-1">
                Waqf pools will appear here when available
              </p>
            </div>
          ) : (
            <div className="grid grid-cols-1 gap-3">
              {pools.map((pool) => (
                <div
                  key={pool.id}
                  className="bg-[#111118] border border-gray-800/60 rounded-2xl p-4"
                >
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-xl bg-sky-900/20 flex items-center justify-center">
                        <Landmark size={18} className="text-sky-400" />
                      </div>
                      <div>
                        <h3 className="text-sm font-semibold text-white">
                          {pool.name}
                        </h3>
                        <p className="text-xs text-gray-500">
                          {pool.beneficiary}
                        </p>
                      </div>
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-2 mb-3">
                    <div className="bg-[#1a1a24] rounded-xl px-3 py-2 text-center">
                      <p className="text-xs text-gray-500">Total Principal</p>
                      <p className="text-sm font-semibold text-white">
                        {pool.totalPrincipal.toLocaleString()} FLH
                      </p>
                    </div>
                    <div className="bg-[#1a1a24] rounded-xl px-3 py-2 text-center">
                      <p className="text-xs text-gray-500">Available Yield</p>
                      <p className="text-sm font-semibold text-emerald-400">
                        {pool.availableYield.toLocaleString()} FLH
                      </p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* b) My Contributions */}
        <div>
          <h2 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
            <Hand size={16} className="text-gray-500" />
            My Contributions
          </h2>
          {contribLoading ? (
            <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>
          ) : contribError ? (
            <ErrorFeedback
              error={contribError}
              kind="default"
              onRetry={fetchContributions}
              context="flh"
            />
          ) : contributions.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 contributions yet
              </p>
              <p className="text-xs text-gray-700 mt-1">
                Your waqf contributions will appear here
              </p>
            </div>
          ) : (
            <div className="space-y-2">
              {contributions.map((c) => (
                <div
                  key={c.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-sky-900/20 flex items-center justify-center">
                      <Landmark size={14} className="text-sky-400" />
                    </div>
                    <div>
                      <p className="text-sm font-medium text-white">
                        {c.amount.toLocaleString()} FLH
                      </p>
                      <p className="text-xs text-gray-500">
                        {c.poolName ?? "Waqf Pool"} —{" "}
                        {new Date(c.createdAt).toLocaleDateString()}
                      </p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* c) Contribute Form */}
        <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">
            <Building2 size={16} className="text-sky-400" />
            Contribute to Waqf
          </h2>
          <form onSubmit={handleContribute} className="space-y-3">
            {pools.length > 0 && (
              <div>
                <label className="text-xs text-gray-500 mb-1.5 block">
                  Select Pool
                </label>
                <select
                  value={selectedPoolId}
                  onChange={(e) => setSelectedPoolId(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-sky-800/50 transition"
                >
                  {pools.map((pool) => (
                    <option key={pool.id} value={pool.id}>
                      {pool.name}
                    </option>
                  ))}
                </select>
              </div>
            )}
            <div>
              <label className="text-xs text-gray-500 mb-1.5 block">
                Amount (FLH)
              </label>
              <input
                type="number"
                min={1}
                step={1}
                value={contributeAmount}
                onChange={(e) => setContributeAmount(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-sky-800/50 focus:ring-1 focus:ring-sky-800/30 transition"
              />
            </div>
            <button
              type="submit"
              disabled={contributeLoading}
              className="w-full px-4 py-4 rounded-xl bg-sky-600 text-white font-semibold text-sm disabled:opacity-50 active:opacity-80 transition flex items-center justify-center gap-2"
            >
              {contributeLoading ? (
                <Loader2 size={16} className="animate-spin" />
              ) : (
                <>
                  <Hand size={16} />
                  Contribute
                </>
              )}
            </button>
          </form>
          {contributeMessage && contributeMessage.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} />
              {contributeMessage.text}
            </div>
          )}
          {contributeMessage && contributeMessage.type === "error" && (
            <ErrorFeedback
              error={contributeMessage.text}
              kind="default"
              onRetry={() => setContributeMessage(null)}
              context="flh"
            />
          )}
        </div>

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