/**
 * app/admin/sales/page.tsx
 * Admin — record a new sale for any agent + view all sales history.
 *
 * ADMIN MODULE — self-contained.
 */

"use client";

import { useEffect, useState, useCallback } from "react";
import { ShoppingBag, Plus, X, RefreshCw, Search, Trash2 } from "lucide-react";
import toast from "react-hot-toast";

interface Agent {
  _id: string;
  name: string;
  email: string;
  referralCode: string;
  isActive: boolean;
}

interface Sale {
  _id: string;
  agentId: { _id: string; name: string; email: string } | null;
  propertyTitle: string;
  saleAmount: number;
  notes?: string;
  commissionsDistributed: boolean;
  createdAt: string;
}

const EMPTY_FORM = { agentId: "", propertyTitle: "", saleAmount: "", notes: "" };

export default function AdminSalesPage() {
  const [sales, setSales] = useState<Sale[]>([]);
  const [agents, setAgents] = useState<Agent[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState(EMPTY_FORM);
  const [query, setQuery] = useState("");

  const loadSales = useCallback(() => {
    setLoading(true);
    fetch("/api/admin/sales")
      .then((r) => r.json())
      .then((d) => {
        if (d.success) {
          setSales(d.data.sales);
          setTotal(d.data.total);
        } else toast.error(d.error ?? "Failed to load sales");
      })
      .catch(() => toast.error("Server error"))
      .finally(() => setLoading(false));
  }, []);

  const loadAgents = useCallback(() => {
    fetch("/api/admin/agents")
      .then((r) => r.json())
      .then((d) => {
        if (d.success) setAgents(d.data.filter((a: Agent) => a.isActive));
      })
      .catch(() => {});
  }, []);

  useEffect(() => {
    loadSales();
    loadAgents();
  }, [loadSales, loadAgents]);

  const handleDelete = async (id: string) => {
    if (!confirm("Are you sure you want to delete this sale? This will revert all associated commissions from agent wallets.")) return;
    
    try {
      const res = await fetch(`/api/admin/sales?id=${id}`, { method: "DELETE" });
      const d = await res.json();
      if (d.success) {
        toast.success("Sale deleted and commissions reverted");
        loadSales();
      } else {
        toast.error(d.error ?? "Failed to delete");
      }
    } catch {
      toast.error("Server error");
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.agentId || !form.propertyTitle || !form.saleAmount) {
      toast.error("Please fill in all required fields");
      return;
    }
    const amount = parseFloat(form.saleAmount);
    if (isNaN(amount) || amount <= 0) {
      toast.error("Enter a valid sale amount");
      return;
    }

    setSubmitting(true);
    try {
      const res = await fetch("/api/admin/sales", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          agentId: form.agentId,
          propertyTitle: form.propertyTitle,
          saleAmount: amount,
          notes: form.notes || undefined,
        }),
      });
      const d = await res.json();
      if (d.success) {
        toast.success("Sale recorded & commissions distributed!");
        setForm(EMPTY_FORM);
        setShowForm(false);
        loadSales();
      } else {
        toast.error(d.error ?? "Failed to record sale");
      }
    } catch {
      toast.error("Server error");
    } finally {
      setSubmitting(false);
    }
  };

  const fmt = (n: number) =>
    `₹${n.toLocaleString("en-IN", { maximumFractionDigits: 0 })}`;

  const filtered = sales.filter(
    (s) =>
      (s.agentId?.name ?? "").toLowerCase().includes(query.toLowerCase()) ||
      s.propertyTitle.toLowerCase().includes(query.toLowerCase())
  );

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <p className="text-[10px] font-black text-slate-400 uppercase tracking-[0.3em] mb-1">Admin</p>
          <h1 className="text-3xl font-black text-black tracking-tight">Sales</h1>
          <p className="text-slate-500 text-sm mt-1 font-medium">{total} total sales recorded</p>
        </div>
        <div className="flex gap-3">
          <button
            onClick={loadSales}
            className="flex items-center gap-2 px-4 py-2.5 rounded-xl bg-indigo-50 text-indigo-600 text-xs font-black uppercase tracking-widest hover:bg-indigo-100 transition-colors border border-indigo-100"
          >
            <RefreshCw className="h-3.5 w-3.5" /> Refresh
          </button>
          <button
            onClick={() => setShowForm(true)}
            className="flex items-center gap-2 px-4 py-2.5 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"
          >
            <Plus className="h-3.5 w-3.5" /> Record Sale
          </button>
        </div>
      </div>

      {/* Add Sale Modal */}
      {showForm && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div
            className="absolute inset-0 bg-black/40 backdrop-blur-sm"
            onClick={() => setShowForm(false)}
          />
          <div className="relative bg-white rounded-2xl shadow-2xl w-full max-w-lg p-6 z-10">
            <div className="flex items-center justify-between mb-5">
              <h2 className="text-lg font-black text-black">Record a Sale</h2>
              <button
                onClick={() => setShowForm(false)}
                className="p-1.5 rounded-lg hover:bg-slate-100 transition-colors"
              >
                <X className="h-4 w-4 text-slate-500" />
              </button>
            </div>

            <form onSubmit={handleSubmit} className="space-y-4">
              {/* Agent selector */}
              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-1.5">
                  Agent *
                </label>
                <select
                  value={form.agentId}
                  onChange={(e) => setForm((f) => ({ ...f, agentId: e.target.value }))}
                  className="w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-black text-sm font-medium focus:outline-none focus:ring-2 focus:ring-black/10"
                  required
                >
                  <option value="">Select an Associate…</option>
                  {agents.map((a) => (
                    <option key={a._id} value={a._id}>
                      {a.name} ({a.email})
                    </option>
                  ))}
                </select>
              </div>

              {/* Property Title */}
              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-1.5">
                  Property / Sale Description *
                </label>
                <input
                  type="text"
                  value={form.propertyTitle}
                  onChange={(e) => setForm((f) => ({ ...f, propertyTitle: e.target.value }))}
                  placeholder="e.g. 3BHK Flat, Bandra West"
                  className="w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-black text-sm font-medium focus:outline-none focus:ring-2 focus:ring-black/10 placeholder-slate-400"
                  required
                />
              </div>

              {/* Sale Amount */}
              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-1.5">
                  Sale Amount (₹) *
                </label>
                <input
                  type="number"
                  min="1"
                  step="0.01"
                  value={form.saleAmount}
                  onChange={(e) => setForm((f) => ({ ...f, saleAmount: e.target.value }))}
                  placeholder="e.g. 5000000"
                  className="w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-black text-sm font-medium focus:outline-none focus:ring-2 focus:ring-black/10 placeholder-slate-400"
                  required
                />
                {form.saleAmount && !isNaN(parseFloat(form.saleAmount)) && (
                  <p className="text-xs text-slate-400 mt-1 font-medium">
                    = {fmt(parseFloat(form.saleAmount))}
                  </p>
                )}
              </div>

              {/* Notes */}
              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-1.5">
                  Notes (optional)
                </label>
                <textarea
                  value={form.notes}
                  onChange={(e) => setForm((f) => ({ ...f, notes: e.target.value }))}
                  rows={2}
                  placeholder="Any additional notes…"
                  className="w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-black text-sm font-medium focus:outline-none focus:ring-2 focus:ring-black/10 placeholder-slate-400 resize-none"
                />
              </div>

              <div className="pt-2 flex gap-3">
                <button
                  type="button"
                  onClick={() => setShowForm(false)}
                  className="flex-1 py-3 rounded-xl border border-slate-200 text-sm font-black text-slate-600 hover:bg-slate-50 transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={submitting}
                  className="flex-1 py-3 rounded-xl bg-indigo-600 text-white text-sm font-black uppercase tracking-widest hover:bg-indigo-700 transition-colors disabled:opacity-60 flex items-center justify-center gap-2 shadow-lg shadow-indigo-600/20"
                >
                  {submitting ? (
                    <><RefreshCw className="h-4 w-4 animate-spin" /> Processing…</>
                  ) : (
                    "Record & Distribute"
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Search */}
      <div className="relative">
        <Search className="absolute left-4 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
        <input
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Search by Associate name or property…"
          className="w-full pl-11 pr-4 py-3 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 font-medium"
        />
      </div>

      {/* Sales Table */}
      <div className="bg-white rounded-2xl border border-slate-100 overflow-hidden">
        {loading ? (
          <div className="space-y-px">
            {[...Array(6)].map((_, i) => (
              <div key={i} className="h-16 bg-slate-50 animate-pulse" />
            ))}
          </div>
        ) : filtered.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 gap-3">
            <ShoppingBag className="h-10 w-10 text-slate-200" />
            <p className="text-slate-400 text-sm font-medium">No sales recorded yet</p>
            <button
              onClick={() => setShowForm(true)}
              className="px-4 py-2 rounded-xl bg-indigo-600 text-white text-xs font-black uppercase tracking-widest mt-2 shadow-lg shadow-indigo-600/20"
            >
              Record First Sale
            </button>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm min-w-[700px]">
              <thead>
                <tr className="border-b border-slate-100 bg-slate-50/50">
                  {["Agent", "Property", "Amount", "Commissions", "Date", "Actions"].map((h) => (
                    <th key={h} className="text-left px-5 py-3 text-[10px] font-black uppercase tracking-widest text-slate-400">
                      {h}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filtered.map((sale) => (
                  <tr key={sale._id} className="border-b border-slate-50 last:border-0 hover:bg-slate-50/30 transition-colors">
                    <td className="px-5 py-4">
                      <p className="font-bold text-black">{sale.agentId?.name ?? "—"}</p>
                      <p className="text-xs text-slate-400">{sale.agentId?.email ?? ""}</p>
                    </td>
                    <td className="px-5 py-4 text-slate-700 font-medium max-w-[200px] truncate">
                      {sale.propertyTitle}
                    </td>
                    <td className="px-5 py-4 font-black text-black">{fmt(sale.saleAmount)}</td>
                    <td className="px-5 py-4">
                      {sale.commissionsDistributed ? (
                        <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-emerald-50 text-emerald-700 text-[10px] font-black border border-emerald-100 uppercase tracking-wide">
                          ✓ Distributed
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-amber-50 text-amber-600 text-[10px] font-black border border-amber-100 uppercase tracking-wide">
                          Pending
                        </span>
                      )}
                    </td>
                    <td className="px-5 py-4 text-slate-400 text-xs font-medium">
                      {new Date(sale.createdAt).toLocaleDateString("en-IN", {
                        day: "numeric", month: "short", year: "numeric",
                      })}
                    </td>
                    <td className="px-5 py-4">
                      <button
                        onClick={() => handleDelete(sale._id)}
                        className="p-2 rounded-lg text-slate-300 hover:text-red-500 hover:bg-red-50 transition-all"
                        title="Delete Sale"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
