"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,
  Gift,
  Clock,
  Check,
  Loader2,
  TrendingUp,
  Heart,
  Repeat,
  X,
} from "lucide-react";
import ErrorFeedback from "@/components/ErrorFeedback";

interface Cause {
  id: string;
  name: string;
  description: string;
  collected: number;
  target: number;
}

interface Subscription {
  id: string;
  causeName?: string;
  amount: number;
  interval: string;
  active: boolean;
  createdAt: string;
}

interface SadaqahPayment {
  id: string;
  amount: number;
  causeName?: string;
  createdAt: string;
}

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

  // Causes
  const [causes, setCauses] = useState<Cause[]>([]);
  const [causesLoading, setCausesLoading] = useState(true);
  const [causesError, setCausesError] = useState<string | null>(null);

  // Give Sadaqah
  const [giveAmount, setGiveAmount] = useState("");
  const [selectedCause, setSelectedCause] = useState("");
  const [isRecurring, setIsRecurring] = useState(false);
  const [recurringInterval, setRecurringInterval] = useState<
    "weekly" | "monthly" | "yearly"
  >("monthly");
  const [giveLoading, setGiveLoading] = useState(false);
  const [giveMessage, setGiveMessage] = useState<{
    type: "success" | "error";
    text: string;
  } | null>(null);

  // Subscriptions
  const [subscriptions, setSubscriptions] = useState<Subscription[]>([]);
  const [subsLoading, setSubsLoading] = useState(true);
  const [subsError, setSubsError] = useState<string | null>(null);
  const [cancelSubId, setCancelSubId] = useState<string | null>(null);

  // History
  const [history, setHistory] = useState<SadaqahPayment[]>([]);
  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) {
      fetchCauses();
      fetchSubscriptions();
      fetchHistory();
    }
  }, [token]);

  const fetchCauses = async () => {
    setCausesLoading(true);
    setCausesError(null);
    try {
      const res = await fetch("/mobile/api/flh/sadaqah/causes");
      if (!res.ok) throw new Error("Failed to fetch causes");
      const data = await res.json();
      setCauses(Array.isArray(data) ? data : data.causes ?? []);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Something went wrong";
      setCausesError(msg);
    } finally {
      setCausesLoading(false);
    }
  };

  const fetchSubscriptions = async () => {
    setSubsLoading(true);
    setSubsError(null);
    try {
      const res = await fetch("/mobile/api/flh/sadaqah/subscriptions", {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (!res.ok) throw new Error("Failed to fetch subscriptions");
      const data = await res.json();
      setSubscriptions(Array.isArray(data) ? data : data.subscriptions ?? []);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Something went wrong";
      setSubsError(msg);
    } finally {
      setSubsLoading(false);
    }
  };

  const fetchHistory = async () => {
    setHistoryLoading(true);
    setHistoryError(null);
    try {
      const res = await fetch("/mobile/api/flh/sadaqah/history", {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (!res.ok) throw new 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 handleGive = async (e: FormEvent) => {
    e.preventDefault();
    const amount = parseFloat(giveAmount);
    if (isNaN(amount) || amount <= 0) {
      setGiveMessage({ type: "error", text: "Please enter a valid amount" });
      return;
    }
    setGiveLoading(true);
    setGiveMessage(null);
    try {
      if (isRecurring) {
        const res = await fetch("/mobile/api/flh/sadaqah/subscribe", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
          body: JSON.stringify({
            amount,
            causeId: selectedCause || undefined,
            interval: recurringInterval,
          }),
        });
        if (!res.ok) {
          const err = await res.json();
          throw new Error(err.error || "Subscription failed");
        }
        setGiveMessage({
          type: "success",
          text: `Recurring sadaqah of ${amount} FLH ${recurringInterval} set up!`,
        });
        fetchSubscriptions();
      } else {
        const res = await fetch("/mobile/api/flh/sadaqah/send", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
          body: JSON.stringify({
            amount,
            causeId: selectedCause || undefined,
          }),
        });
        if (!res.ok) {
          const err = await res.json();
          throw new Error(err.error || "Sadaqah failed");
        }
        setGiveMessage({
          type: "success",
          text: `Sadaqah of ${amount} FLH given! May Allah accept it.`,
        });
        fetchHistory();
      }
      setGiveAmount("");
      setTimeout(() => setGiveMessage(null), 4000);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Transaction failed";
      setGiveMessage({ type: "error", text: msg });
      setTimeout(() => setGiveMessage(null), 4000);
    } finally {
      setGiveLoading(false);
    }
  };

  const handleCancelSubscription = async (subscriptionId: string) => {
    setCancelSubId(subscriptionId);
    try {
      const res = await fetch("/mobile/api/flh/sadaqah/unsubscribe", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ subscriptionId }),
      });
      if (!res.ok) throw new Error("Failed to cancel");
      fetchSubscriptions();
    } catch {
      // ignore
    } finally {
      setCancelSubId(null);
    }
  };

  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">Sadaqah</h1>
          <p className="text-xs text-gray-500">Voluntary charity</p>
        </div>
      </div>

      <div className="px-4 space-y-5 animate-fade-in">
        {/* a) Causes Grid */}
        <div>
          <h2 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
            <Heart size={16} className="text-emerald-400" />
            Causes
          </h2>
          {causesLoading ? (
            <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>
          ) : causesError ? (
            <ErrorFeedback
              error={causesError}
              kind="default"
              onRetry={fetchCauses}
              context="flh"
            />
          ) : causes.length === 0 ? (
            <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5 text-center">
              <Gift size={20} className="mx-auto text-gray-700 mb-2" />
              <p className="text-sm text-gray-500">No causes available</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 gap-3">
              {causes.map((cause) => {
                const progress =
                  cause.target > 0
                    ? Math.min(100, (cause.collected / cause.target) * 100)
                    : 0;
                return (
                  <div
                    key={cause.id}
                    className="bg-[#111118] border border-gray-800/60 rounded-2xl p-4"
                  >
                    <div className="flex items-start justify-between mb-2">
                      <div>
                        <h3 className="text-sm font-semibold text-white">
                          {cause.name}
                        </h3>
                        <p className="text-xs text-gray-500 mt-0.5">
                          {cause.description}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center justify-between text-xs text-gray-500 mb-2">
                      <span>
                        {cause.collected.toLocaleString()} /{" "}
                        {cause.target.toLocaleString()} FLH
                      </span>
                      <span>{progress.toFixed(0)}%</span>
                    </div>
                    <div className="w-full h-2 bg-gray-800/60 rounded-full overflow-hidden">
                      <div
                        className="h-full bg-gradient-to-r from-emerald-500 to-emerald-400 rounded-full transition-all"
                        style={{ width: `${progress}%` }}
                      />
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* b) Give Sadaqah */}
        <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">
            <Gift size={16} className="text-emerald-400" />
            Give Sadaqah
          </h2>
          <form onSubmit={handleGive} 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={giveAmount}
                onChange={(e) => setGiveAmount(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-emerald-800/50 focus:ring-1 focus:ring-emerald-800/30 transition"
              />
            </div>
            {causes.length > 0 && (
              <div>
                <label className="text-xs text-gray-500 mb-1.5 block">
                  Cause (optional)
                </label>
                <select
                  value={selectedCause}
                  onChange={(e) => setSelectedCause(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-emerald-800/50 transition"
                >
                  <option value="">General Sadaqah</option>
                  {causes.map((cause) => (
                    <option key={cause.id} value={cause.id}>
                      {cause.name}
                    </option>
                  ))}
                </select>
              </div>
            )}
            {/* Recurring Toggle */}
            <div className="flex items-center justify-between">
              <label className="text-xs text-gray-500 flex items-center gap-2">
                <Repeat size={14} />
                Make recurring
              </label>
              <button
                type="button"
                onClick={() => setIsRecurring(!isRecurring)}
                className={`relative w-10 h-5 rounded-full transition-colors ${
                  isRecurring ? "bg-emerald-600" : "bg-gray-700"
                }`}
              >
                <span
                  className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${
                    isRecurring ? "translate-x-[22px]" : "translate-x-0.5"
                  }`}
                />
              </button>
            </div>
            {isRecurring && (
              <div>
                <label className="text-xs text-gray-500 mb-1.5 block">
                  Interval
                </label>
                <select
                  value={recurringInterval}
                  onChange={(e) =>
                    setRecurringInterval(
                      e.target.value as "weekly" | "monthly" | "yearly"
                    )
                  }
                  className="w-full bg-[#1a1a24] border border-gray-800/60 rounded-xl px-4 py-4 text-white focus:outline-none focus:border-emerald-800/50 transition"
                >
                  <option value="weekly">Weekly</option>
                  <option value="monthly">Monthly</option>
                  <option value="yearly">Yearly</option>
                </select>
              </div>
            )}
            <button
              type="submit"
              disabled={giveLoading}
              className="w-full px-4 py-4 rounded-xl bg-emerald-600 text-white font-semibold text-sm disabled:opacity-50 active:opacity-80 transition flex items-center justify-center gap-2"
            >
              {giveLoading ? (
                <Loader2 size={16} className="animate-spin" />
              ) : (
                <>
                  <Gift size={16} />
                  {isRecurring ? "Subscribe" : "Give Sadaqah"}
                </>
              )}
            </button>
          </form>
          {giveMessage && giveMessage.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} />
              {giveMessage.text}
            </div>
          )}
          {giveMessage && giveMessage.type === "error" && (
            <ErrorFeedback
              error={giveMessage.text}
              kind="default"
              onRetry={() => setGiveMessage(null)}
              context="flh"
            />
          )}
        </div>

        {/* c) Recurring Subscriptions */}
        <div>
          <h2 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
            <Repeat size={16} className="text-gray-500" />
            Recurring Subscriptions
          </h2>
          {subsLoading ? (
            <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>
          ) : subsError ? (
            <ErrorFeedback
              error={subsError}
              kind="default"
              onRetry={fetchSubscriptions}
              context="flh"
            />
          ) : subscriptions.length === 0 ? (
            <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5 text-center">
              <Repeat size={20} className="mx-auto text-gray-700 mb-2" />
              <p className="text-sm text-gray-500">No active subscriptions</p>
              <p className="text-xs text-gray-700 mt-1">
                Set up recurring sadaqah for continuous rewards
              </p>
            </div>
          ) : (
            <div className="space-y-2">
              {subscriptions
                .filter((s) => s.active)
                .map((sub) => (
                  <div
                    key={sub.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-emerald-900/20 flex items-center justify-center">
                        <Repeat size={14} className="text-emerald-400" />
                      </div>
                      <div>
                        <p className="text-sm font-medium text-white">
                          {sub.amount.toLocaleString()} FLH / {sub.interval}
                        </p>
                        <p className="text-xs text-gray-500">
                          {sub.causeName ?? "General Sadaqah"}
                        </p>
                      </div>
                    </div>
                    <button
                      onClick={() => handleCancelSubscription(sub.id)}
                      disabled={cancelSubId === sub.id}
                      className="px-3 py-1.5 rounded-lg bg-red-900/20 border border-red-800/30 text-red-400 text-xs font-medium active:scale-95 transition disabled:opacity-50"
                    >
                      {cancelSubId === sub.id ? (
                        <Loader2 size={12} className="animate-spin" />
                      ) : (
                        "Cancel"
                      )}
                    </button>
                  </div>
                ))}
            </div>
          )}
        </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" />
            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 sadaqah yet</p>
              <p className="text-xs text-gray-700 mt-1">
                Your sadaqah 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-emerald-900/20 flex items-center justify-center">
                      <Gift size={14} className="text-emerald-400" />
                    </div>
                    <div>
                      <p className="text-sm font-medium text-white">
                        {payment.amount.toLocaleString()} FLH
                      </p>
                      <p className="text-xs text-gray-500">
                        {payment.causeName ?? "General Sadaqah"} —{" "}
                        {new Date(payment.createdAt).toLocaleDateString()}
                      </p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

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