/**
 * app/admin/transfer/page.tsx
 * Admin — Transfer an agent (with entire downline) under a new sponsor.
 *
 * ADMIN MODULE — self-contained.
 */

"use client";

import { useState } from "react";
import {
  ArrowRightLeft,
  Search,
  AlertTriangle,
  CheckCircle2,
  RefreshCw,
  Users,
  ArrowDown,
  Shield,
} from "lucide-react";
import toast from "react-hot-toast";

interface TransferResult {
  agent: string;
  agentEmail: string;
  oldSponsor: string;
  newSponsor: string;
  newLevel: number;
  teamMembersMoved: number;
}

export default function AdminTransferPage() {
  const [agentEmail, setAgentEmail] = useState("");
  const [newParentEmail, setNewParentEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<TransferResult | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [showConfirm, setShowConfirm] = useState(false);

  const handlePreview = () => {
    setError(null);
    setResult(null);

    if (!agentEmail.trim()) {
      setError("Please enter the agent's email address");
      return;
    }
    if (!newParentEmail.trim()) {
      setError("Please enter the new parent's email address");
      return;
    }
    if (
      agentEmail.trim().toLowerCase() === newParentEmail.trim().toLowerCase()
    ) {
      setError("Cannot transfer an agent under themselves");
      return;
    }
    setShowConfirm(true);
  };

  const handleTransfer = async () => {
    setShowConfirm(false);
    setLoading(true);
    setError(null);
    setResult(null);

    try {
      const res = await fetch("/api/admin/transfer-agent", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          agentEmail: agentEmail.trim(),
          newParentEmail: newParentEmail.trim(),
        }),
      });
      const d = await res.json();
      if (d.success) {
        setResult(d.data);
        toast.success(d.message);
        setAgentEmail("");
        setNewParentEmail("");
      } else {
        setError(d.error ?? "Transfer failed");
        toast.error(d.error ?? "Transfer failed");
      }
    } catch {
      setError("Server error — please try again");
      toast.error("Server error");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6 max-w-4xl mx-auto">
      {/* Header */}
      <div>
        <p className="text-[10px] font-black text-slate-400 uppercase tracking-[0.3em] mb-1">
          Admin Control
        </p>
        <h1 className="text-3xl font-black text-black tracking-tight">
          Transfer Associate / Team
        </h1>
        <p className="text-sm text-slate-500 mt-1">
          Move an associate along with their entire downline team under a different sponsor.
        </p>
      </div>

      {/* Warning Banner */}
      <div className="flex items-start gap-3 px-5 py-4 rounded-2xl bg-amber-50 border border-amber-100">
        <AlertTriangle className="h-5 w-5 text-amber-500 flex-shrink-0 mt-0.5" />
        <div>
          <p className="text-sm font-bold text-amber-800">Tree Structure Reorganization</p>
          <p className="text-xs text-amber-700 mt-1 leading-relaxed">
            This operation moves the selected associate and all their downline members under the new parent sponsor.
            All member levels in their subtree will automatically adjust to match their new depth in the tree.
          </p>
        </div>
      </div>

      {/* Form Card */}
      <div className="bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden">
        <div className="px-6 py-5 border-b border-slate-100 bg-slate-50/50">
          <h2 className="text-[10px] font-black uppercase tracking-widest text-slate-400 flex items-center gap-2">
            <ArrowRightLeft className="h-3.5 w-3.5" />
            Transfer Parameters
          </h2>
        </div>

        <div className="p-6 space-y-6">
          {/* Agent to move */}
          <div className="space-y-2">
            <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500">
              Associate to Move (Email Address)
            </label>
            <div className="relative">
              <Search className="absolute left-4 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
              <input
                type="email"
                value={agentEmail}
                onChange={(e) => {
                  setAgentEmail(e.target.value);
                  setError(null);
                  setResult(null);
                }}
                placeholder="e.g. arifkhan250@gmail.com"
                className="w-full pl-11 pr-4 py-3.5 rounded-xl border border-slate-200 bg-white text-slate-900 text-sm placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-indigo-600/10 focus:border-indigo-300 font-medium transition-all"
              />
            </div>
            <p className="text-[10px] text-slate-400 font-medium">
              This associate and all of their downline members will be shifted.
            </p>
          </div>

          {/* Arrow */}
          <div className="flex justify-center">
            <div className="h-10 w-10 rounded-full bg-indigo-50 border border-indigo-100 flex items-center justify-center">
              <ArrowDown className="h-4 w-4 text-indigo-500" />
            </div>
          </div>

          {/* New Parent */}
          <div className="space-y-2">
            <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500">
              New Parent / Sponsor (Email Address)
            </label>
            <div className="relative">
              <Search className="absolute left-4 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
              <input
                type="email"
                value={newParentEmail}
                onChange={(e) => {
                  setNewParentEmail(e.target.value);
                  setError(null);
                  setResult(null);
                }}
                placeholder="e.g. nikkisingh250@gmail.com"
                className="w-full pl-11 pr-4 py-3.5 rounded-xl border border-slate-200 bg-white text-slate-900 text-sm placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-indigo-600/10 focus:border-indigo-300 font-medium transition-all"
              />
            </div>
            <p className="text-[10px] text-slate-400 font-medium">
              The associate will be placed directly in this sponsor&apos;s direct downline.
            </p>
          </div>

          {/* Error message */}
          {error && (
            <div className="flex items-center gap-2 px-4 py-3 rounded-xl bg-red-50 border border-red-100">
              <AlertTriangle className="h-4 w-4 text-red-500 flex-shrink-0" />
              <p className="text-sm text-red-600 font-medium">{error}</p>
            </div>
          )}

          {/* Success Result */}
          {result && (
            <div className="rounded-2xl bg-emerald-50 border border-emerald-100 overflow-hidden">
              <div className="px-5 py-3 border-b border-emerald-100 flex items-center gap-2">
                <CheckCircle2 className="h-4 w-4 text-emerald-600" />
                <p className="text-sm font-bold text-emerald-800">Transfer Completed Successfully</p>
              </div>
              <div className="p-5 space-y-3">
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div>
                    <p className="text-[10px] font-black uppercase tracking-widest text-emerald-500 mb-0.5">
                      Associate
                    </p>
                    <p className="font-bold text-emerald-900">{result.agent}</p>
                    <p className="text-xs text-emerald-600">{result.agentEmail}</p>
                  </div>
                  <div>
                    <p className="text-[10px] font-black uppercase tracking-widest text-emerald-500 mb-0.5">
                      New Tree Level
                    </p>
                    <p className="font-bold text-emerald-900">Level {result.newLevel}</p>
                  </div>
                  <div>
                    <p className="text-[10px] font-black uppercase tracking-widest text-emerald-500 mb-0.5">
                      Previous Sponsor
                    </p>
                    <p className="font-bold text-emerald-900">{result.oldSponsor}</p>
                  </div>
                  <div>
                    <p className="text-[10px] font-black uppercase tracking-widest text-emerald-500 mb-0.5">
                      New Sponsor
                    </p>
                    <p className="font-bold text-emerald-900">{result.newSponsor}</p>
                  </div>
                </div>
                <div className="flex items-center gap-2 pt-2 border-t border-emerald-100">
                  <Users className="h-4 w-4 text-emerald-600" />
                  <p className="text-sm text-emerald-800 font-medium">
                    <span className="font-bold">{result.teamMembersMoved}</span> member(s) shifted to new position.
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Action Button */}
          <div className="pt-2">
            <button
              onClick={handlePreview}
              disabled={loading || !agentEmail.trim() || !newParentEmail.trim()}
              className="w-full flex items-center justify-center gap-2 px-6 py-3.5 rounded-xl bg-indigo-600 text-white text-xs font-black uppercase tracking-widest hover:bg-indigo-700 transition-all shadow-lg shadow-indigo-600/20 disabled:opacity-50 disabled:cursor-not-allowed active:scale-[0.99]"
            >
              {loading ? (
                <>
                  <RefreshCw className="h-3.5 w-3.5 animate-spin" />
                  Processing Transfer...
                </>
              ) : (
                <>
                  <ArrowRightLeft className="h-3.5 w-3.5" />
                  Transfer Associate & Team
                </>
              )}
            </button>
          </div>
        </div>
      </div>

      {/* Confirmation Modal */}
      {showConfirm && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div
            className="absolute inset-0 bg-slate-900/60 backdrop-blur-sm"
            onClick={() => setShowConfirm(false)}
          />
          <div className="relative bg-white rounded-2xl border border-slate-100 shadow-2xl max-w-md w-full overflow-hidden">
            <div className="px-6 py-5 border-b border-slate-100 bg-slate-50/50">
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 rounded-xl bg-amber-50 border border-amber-100 flex items-center justify-center">
                  <Shield className="h-5 w-5 text-amber-500" />
                </div>
                <div>
                  <h3 className="font-black text-black text-sm">Confirm Transfer</h3>
                  <p className="text-xs text-slate-400 mt-0.5">
                    This will re-link the associate in the MLM tree
                  </p>
                </div>
              </div>
            </div>
            <div className="p-6 space-y-4">
              <p className="text-sm text-slate-600 leading-relaxed">
                You are about to transfer:
              </p>
              <div className="bg-slate-50 rounded-xl p-4 space-y-3 border border-slate-100">
                <div>
                  <p className="text-[10px] font-black uppercase tracking-widest text-slate-400">
                    Associate
                  </p>
                  <p className="text-sm font-bold text-black mt-0.5">{agentEmail}</p>
                </div>
                <div className="flex justify-center">
                  <ArrowDown className="h-4 w-4 text-indigo-400" />
                </div>
                <div>
                  <p className="text-[10px] font-black uppercase tracking-widest text-slate-400">
                    New Sponsor
                  </p>
                  <p className="text-sm font-bold text-black mt-0.5">{newParentEmail}</p>
                </div>
              </div>
              <p className="text-xs text-slate-500 leading-relaxed">
                The associate and their entire team hierarchy will be moved under this new sponsor.
              </p>
              <div className="flex gap-3 pt-2">
                <button
                  onClick={() => setShowConfirm(false)}
                  className="flex-1 px-4 py-3 rounded-xl border border-slate-200 text-xs font-black uppercase tracking-widest text-slate-600 hover:bg-slate-50 transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handleTransfer}
                  className="flex-1 px-4 py-3 rounded-xl bg-indigo-600 text-white text-xs font-black uppercase tracking-widest hover:bg-indigo-700 transition-colors shadow-lg shadow-indigo-600/20"
                >
                  Confirm & Transfer
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
