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

interface SentHibah {
  id: string;
  toUserId?: string;
  toEmail?: string;
  amount: number;
  message?: string;
  status: string;
  createdAt: string;
}

interface ReceivedHibah {
  id: string;
  fromUserId?: string;
  fromEmail?: string;
  fromName?: string;
  amount: number;
  message?: string;
  status: string;
  createdAt: string;
}

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

  // Send form
  const [toEmail, setToEmail] = useState("");
  const [sendAmount, setSendAmount] = useState("");
  const [sendMessage, setSendMessage] = useState("");
  const [sendLoading, setSendLoading] = useState(false);
  const [sendMessageState, setSendMessageState] = useState<{
    type: "success" | "error";
    text: string;
  } | null>(null);

  // Sent
  const [sent, setSent] = useState<SentHibah[]>([]);
  const [sentLoading, setSentLoading] = useState(true);
  const [sentError, setSentError] = useState<string | null>(null);

  // Received
  const [received, setReceived] = useState<ReceivedHibah[]>([]);
  const [receivedLoading, setReceivedLoading] = useState(true);
  const [receivedError, setReceivedError] = useState<string | null>(null);

  // Accept/Reject
  const [actionLoadingId, setActionLoadingId] = useState<string | null>(null);

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

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

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

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

  const handleSend = async (e: FormEvent) => {
    e.preventDefault();
    const amount = parseFloat(sendAmount);
    if (isNaN(amount) || amount <= 0) {
      setSendMessageState({
        type: "error",
        text: "Please enter a valid amount",
      });
      return;
    }
    if (!toEmail.trim()) {
      setSendMessageState({
        type: "error",
        text: "Please enter recipient email",
      });
      return;
    }
    setSendLoading(true);
    setSendMessageState(null);
    try {
      const res = await fetch("/mobile/api/flh/hibah/send", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          toEmail: toEmail.trim(),
          amount,
          message: sendMessage.trim() || undefined,
        }),
      });
      if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || "Failed to send hibah");
      }
      setSendMessageState({
        type: "success",
        text: `Hibah of ${amount} FLH sent to ${toEmail}!`,
      });
      setToEmail("");
      setSendAmount("");
      setSendMessage("");
      fetchSent();
      setTimeout(() => setSendMessageState(null), 4000);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Failed to send";
      setSendMessageState({ type: "error", text: msg });
      setTimeout(() => setSendMessageState(null), 4000);
    } finally {
      setSendLoading(false);
    }
  };

  const handleAccept = async (hibahId: string) => {
    setActionLoadingId(hibahId);
    try {
      const res = await fetch("/mobile/api/flh/hibah/accept", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ hibahId }),
      });
      if (!res.ok) throw new Error("Failed to accept");
      fetchReceived();
    } catch {
      // ignore
    } finally {
      setActionLoadingId(null);
    }
  };

  const handleReject = async (hibahId: string) => {
    setActionLoadingId(hibahId);
    try {
      const res = await fetch(`/mobile/api/flh/hibah/reject/${hibahId}`, {
        method: "POST",
        headers: { Authorization: `Bearer ${token}` },
      });
      if (!res.ok) throw new Error("Failed to reject");
      fetchReceived();
    } catch {
      // ignore
    } finally {
      setActionLoadingId(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;

  const statusIcon = (status: string) => {
    switch (status) {
      case "accepted":
        return <Check size={14} className="text-emerald-400" />;
      case "rejected":
        return <X size={14} className="text-red-400" />;
      default:
        return <Clock size={14} className="text-amber-400" />;
    }
  };

  const statusColor = (status: string) => {
    switch (status) {
      case "accepted":
        return "text-emerald-400";
      case "rejected":
        return "text-red-400";
      default:
        return "text-amber-400";
    }
  };

  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">Hibah</h1>
          <p className="text-xs text-gray-500">Give gifts to loved ones</p>
        </div>
      </div>

      <div className="px-4 space-y-5 animate-fade-in">
        {/* a) Send Hibah */}
        <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">
            <Send size={16} className="text-rose-400" />
            Send Hibah
          </h2>
          <form onSubmit={handleSend} className="space-y-3">
            <div>
              <label className="text-xs text-gray-500 mb-1.5 block">
                Recipient Email
              </label>
              <input
                type="email"
                value={toEmail}
                onChange={(e) => setToEmail(e.target.value)}
                placeholder="friend@example.com"
                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-rose-800/50 focus:ring-1 focus:ring-rose-800/30 transition"
              />
            </div>
            <div>
              <label className="text-xs text-gray-500 mb-1.5 block">
                Amount (FLH)
              </label>
              <input
                type="number"
                min={1}
                step={1}
                value={sendAmount}
                onChange={(e) => setSendAmount(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-rose-800/50 focus:ring-1 focus:ring-rose-800/30 transition"
              />
            </div>
            <div>
              <label className="text-xs text-gray-500 mb-1.5 block">
                Message (optional)
              </label>
              <textarea
                value={sendMessage}
                onChange={(e) => setSendMessage(e.target.value)}
                placeholder="A kind note..."
                rows={2}
                className="w-full bg-[#1a1a24] border border-gray-800/60 rounded-xl px-4 py-3 text-white placeholder-gray-600 focus:outline-none focus:border-rose-800/50 focus:ring-1 focus:ring-rose-800/30 transition resize-none"
              />
            </div>
            <button
              type="submit"
              disabled={sendLoading}
              className="w-full px-4 py-4 rounded-xl bg-rose-600 text-white font-semibold text-sm disabled:opacity-50 active:opacity-80 transition flex items-center justify-center gap-2"
            >
              {sendLoading ? (
                <Loader2 size={16} className="animate-spin" />
              ) : (
                <>
                  <Heart size={16} />
                  Send Hibah
                </>
              )}
            </button>
          </form>
          {sendMessageState && sendMessageState.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} />
              {sendMessageState.text}
            </div>
          )}
          {sendMessageState && sendMessageState.type === "error" && (
            <ErrorFeedback
              error={sendMessageState.text}
              kind="default"
              onRetry={() => setSendMessageState(null)}
              context="flh"
            />
          )}
        </div>

        {/* b) Sent Gifts */}
        <div>
          <h2 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
            <ArrowUpRight size={16} className="text-gray-500" />
            Sent Gifts
          </h2>
          {sentLoading ? (
            <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>
          ) : sentError ? (
            <ErrorFeedback
              error={sentError}
              kind="default"
              onRetry={fetchSent}
              context="flh"
            />
          ) : sent.length === 0 ? (
            <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5 text-center">
              <ArrowUpRight size={20} className="mx-auto text-gray-700 mb-2" />
              <p className="text-sm text-gray-500">No gifts sent yet</p>
              <p className="text-xs text-gray-700 mt-1">
                Your outgoing hibah will appear here
              </p>
            </div>
          ) : (
            <div className="space-y-2">
              {sent.map((gift) => (
                <div
                  key={gift.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-rose-900/20 flex items-center justify-center">
                      <ArrowUpRight size={14} className="text-rose-400" />
                    </div>
                    <div>
                      <p className="text-sm font-medium text-white">
                        {gift.amount.toLocaleString()} FLH
                      </p>
                      <p className="text-xs text-gray-500">
                        To: {gift.toEmail ?? gift.toUserId ?? "Unknown"} —{" "}
                        {new Date(gift.createdAt).toLocaleDateString()}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-1.5">
                    {statusIcon(gift.status)}
                    <span
                      className={`text-xs font-medium capitalize ${statusColor(gift.status)}`}
                    >
                      {gift.status}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* c) Received Gifts */}
        <div>
          <h2 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
            <ArrowDownLeft size={16} className="text-gray-500" />
            Received Gifts
          </h2>
          {receivedLoading ? (
            <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>
          ) : receivedError ? (
            <ErrorFeedback
              error={receivedError}
              kind="default"
              onRetry={fetchReceived}
              context="flh"
            />
          ) : received.length === 0 ? (
            <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5 text-center">
              <ArrowDownLeft
                size={20}
                className="mx-auto text-gray-700 mb-2"
              />
              <p className="text-sm text-gray-500">No gifts received yet</p>
              <p className="text-xs text-gray-700 mt-1">
                When someone sends you a hibah, it will appear here
              </p>
            </div>
          ) : (
            <div className="space-y-2">
              {received.map((gift) => (
                <div
                  key={gift.id}
                  className="bg-[#111118] border border-gray-800/60 rounded-xl px-4 py-3"
                >
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center gap-3">
                      <div className="w-8 h-8 rounded-full bg-emerald-900/20 flex items-center justify-center">
                        <ArrowDownLeft
                          size={14}
                          className="text-emerald-400"
                        />
                      </div>
                      <div>
                        <p className="text-sm font-medium text-white">
                          {gift.amount.toLocaleString()} FLH
                        </p>
                        <p className="text-xs text-gray-500">
                          From: {gift.fromName ?? gift.fromEmail ?? "Unknown"}{" "}
                          —{" "}
                          {new Date(gift.createdAt).toLocaleDateString()}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-1.5">
                      {statusIcon(gift.status)}
                      <span
                        className={`text-xs font-medium capitalize ${statusColor(gift.status)}`}
                      >
                        {gift.status}
                      </span>
                    </div>
                  </div>
                  {gift.message && (
                    <p className="text-xs text-gray-500 ml-11 mb-2 italic">
                      &ldquo;{gift.message}&rdquo;
                    </p>
                  )}
                  {gift.status === "pending" && (
                    <div className="flex gap-2 ml-11">
                      <button
                        onClick={() => handleAccept(gift.id)}
                        disabled={actionLoadingId === gift.id}
                        className="flex-1 px-3 py-2 rounded-lg bg-emerald-600 text-white text-xs font-medium active:scale-95 transition disabled:opacity-50 flex items-center justify-center gap-1"
                      >
                        {actionLoadingId === gift.id ? (
                          <Loader2 size={12} className="animate-spin" />
                        ) : (
                          <>
                            <Check size={12} />
                            Accept
                          </>
                        )}
                      </button>
                      <button
                        onClick={() => handleReject(gift.id)}
                        disabled={actionLoadingId === gift.id}
                        className="flex-1 px-3 py-2 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 flex items-center justify-center gap-1"
                      >
                        {actionLoadingId === gift.id ? (
                          <Loader2 size={12} className="animate-spin" />
                        ) : (
                          <>
                            <X size={12} />
                            Reject
                          </>
                        )}
                      </button>
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>

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