"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { RefreshCw, ArrowLeftRight, CheckCircle, Plus } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
import { Badge } from "@/components/ui/Badge";
import { Button } from "@/components/ui/Button";
import { Modal } from "@/components/ui/Modal";
import { formatDate, formatCurrency } from "@/lib/utils";
import api from "@/lib/api";
import { toast } from "sonner";

interface Payment {
  id: string; clientId: string; amount: string; channel: string;
  paymentDate?: string; createdAt: string;
  client?: { firstName: string; lastName: string; accountNumber: string };
}
interface Remittance {
  id: string; collectorId?: string;
  collector?: { firstName: string; lastName: string };
  amount: number | string; notes?: string; status: string;
  payments?: Payment[]; createdAt: string;
}

const statusVariant: Record<string, "success" | "warning" | "muted"> = {
  CONFIRMED: "success", PENDING: "warning", DISPUTED: "muted",
};

export default function RemittancesPage() {
  const qc = useQueryClient();
  const [showSubmit, setShowSubmit] = useState(false);
  const [notes, setNotes] = useState("");
  const [selectedPaymentIds, setSelectedPaymentIds] = useState<string[]>([]);
  const [selected, setSelected] = useState<Remittance | null>(null);

  const { data: remittances = [], isLoading, refetch } = useQuery<Remittance[]>({
    queryKey: ["remittances"],
    queryFn: async () => {
      const res = await api.get("/api/v1/remittances?limit=50");
      const d = res.data;
      return Array.isArray(d) ? d : d.data ?? [];
    },
  });

  const { data: unremitted = [] } = useQuery<Payment[]>({
    queryKey: ["unremitted-payments"],
    queryFn: async () => {
      const res = await api.get<Payment[]>("/api/v1/payments/unremitted");
      return Array.isArray(res.data) ? res.data : (res.data as any).data ?? [];
    },
    enabled: showSubmit,
  });

  const confirm = useMutation({
    mutationFn: async (id: string) => { await api.patch(`/api/v1/remittances/${id}/confirm`); },
    onSuccess: () => { toast.success("Remittance confirmed!"); qc.invalidateQueries({ queryKey: ["remittances"] }); },
    onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to confirm"),
  });

  const submitRemittance = useMutation({
    mutationFn: async () => {
      await api.post("/api/v1/remittances", { paymentIds: selectedPaymentIds, notes: notes || undefined });
    },
    onSuccess: () => {
      toast.success("Remittance submitted!");
      setShowSubmit(false);
      setSelectedPaymentIds([]);
      setNotes("");
      qc.invalidateQueries({ queryKey: ["remittances"] });
      qc.invalidateQueries({ queryKey: ["unremitted-payments"] });
    },
    onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to submit remittance"),
  });

  const togglePayment = (id: string) => {
    setSelectedPaymentIds(prev =>
      prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
    );
  };

  const selectedTotal = unremitted
    .filter(p => selectedPaymentIds.includes(p.id))
    .reduce((sum, p) => sum + Number(p.amount), 0);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Remittances</h1>
          <p className="text-sm text-gray-500 mt-1">{remittances.length} remittances</p>
        </div>
        <div className="flex gap-2">
          <Button onClick={() => refetch()} variant="outline" size="sm"><RefreshCw size={14} className="mr-1" />Refresh</Button>
          <Button onClick={() => setShowSubmit(true)} size="sm"><Plus size={14} className="mr-1" />Submit Remittance</Button>
        </div>
      </div>

      <Card>
        <CardContent className="p-0">
          <Table>
            <TableHead>
              <TableRow><Th>Date</Th><Th>Collector</Th><Th>Amount</Th><Th>Status</Th><Th>Notes</Th><Th></Th></TableRow>
            </TableHead>
            <TableBody>
              {isLoading ? (
                Array.from({ length: 5 }).map((_, i) => (
                  <TableRow key={i}><Td colSpan={6}><div className="h-4 bg-gray-100 rounded animate-pulse" /></Td></TableRow>
                ))
              ) : remittances.length === 0 ? (
                <EmptyState colSpan={6} message="No remittances yet" icon={<ArrowLeftRight size={24} />} />
              ) : remittances.map(r => (
                <TableRow key={r.id} onClick={() => setSelected(r)} className="cursor-pointer hover:bg-blue-50 transition-colors">
                  <Td>{formatDate(r.createdAt)}</Td>
                  <Td className="font-medium">{r.collector ? `${r.collector.firstName} ${r.collector.lastName}` : "—"}</Td>
                  <Td className="font-semibold text-blue-700">{formatCurrency(Number(r.amount))}</Td>
                  <Td><Badge variant={statusVariant[r.status] ?? "muted"}>{r.status}</Badge></Td>
                  <Td className="text-gray-500 text-sm">{r.notes ?? "—"}</Td>
                  <Td>
                    {r.status === "PENDING" && (
                      <Button size="sm" variant="secondary" onClick={e => { e.stopPropagation(); confirm.mutate(r.id); }}>
                        <CheckCircle size={13} className="mr-1" />Confirm
                      </Button>
                    )}
                  </Td>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Remittance Detail Modal */}
      <Modal isOpen={!!selected} onClose={() => setSelected(null)} title="Remittance Details" className="max-w-lg">
        {selected && (
          <div className="space-y-4">
            <div className="bg-gray-50 rounded-lg p-4 space-y-2 text-sm">
              <div className="flex justify-between"><span className="text-gray-500">Collector</span>
                <span className="font-medium">{selected.collector ? `${selected.collector.firstName} ${selected.collector.lastName}` : "—"}</span></div>
              <div className="flex justify-between"><span className="text-gray-500">Total Amount</span>
                <span className="text-lg font-bold text-blue-700">{formatCurrency(Number(selected.amount))}</span></div>
              <div className="flex justify-between"><span className="text-gray-500">Status</span>
                <Badge variant={statusVariant[selected.status] ?? "muted"}>{selected.status}</Badge></div>
              <div className="flex justify-between"><span className="text-gray-500">Date</span>
                <span>{formatDate(selected.createdAt)}</span></div>
              {selected.notes && <div className="flex justify-between"><span className="text-gray-500">Notes</span><span>{selected.notes}</span></div>}
            </div>
            {selected.payments && selected.payments.length > 0 && (
              <div>
                <p className="text-sm font-medium text-gray-700 mb-2">Included Payments ({selected.payments.length})</p>
                <div className="space-y-1.5 max-h-48 overflow-y-auto">
                  {selected.payments.map(p => (
                    <div key={p.id} className="flex justify-between text-sm bg-white border rounded-lg px-3 py-2">
                      <span className="text-gray-600">{p.client ? `${p.client.firstName} ${p.client.lastName}` : p.clientId.slice(0, 8)}</span>
                      <span className="font-medium text-green-700">{formatCurrency(Number(p.amount))}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
            <div className="flex justify-between pt-1">
              {selected.status === "PENDING" && (
                <Button size="sm" onClick={() => { confirm.mutate(selected.id); setSelected(null); }} isLoading={confirm.isPending}>
                  <CheckCircle size={14} className="mr-1" />Confirm
                </Button>
              )}
              <Button variant="outline" size="sm" onClick={() => setSelected(null)} className="ml-auto">Close</Button>
            </div>
          </div>
        )}
      </Modal>

      {/* Submit Remittance Modal */}
      <Modal isOpen={showSubmit} onClose={() => setShowSubmit(false)} title="Submit Remittance" className="max-w-xl">
        <div className="space-y-4">
          <p className="text-sm text-gray-500">Select payments to include in this remittance.</p>
          {unremitted.length === 0 ? (
            <div className="text-center py-6 text-gray-400">No unremitted payments available.</div>
          ) : (
            <>
              <div className="flex justify-between items-center">
                <span className="text-sm font-medium text-gray-700">{unremitted.length} unremitted payments</span>
                <button onClick={() => setSelectedPaymentIds(unremitted.map(p => p.id))}
                  className="text-xs text-blue-600 hover:underline">Select All</button>
              </div>
              <div className="space-y-1.5 max-h-64 overflow-y-auto border rounded-lg p-2">
                {unremitted.map(p => (
                  <label key={p.id} className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${selectedPaymentIds.includes(p.id) ? "bg-blue-50 border border-blue-200" : "hover:bg-gray-50 border border-transparent"}`}>
                    <div className="flex items-center gap-2">
                      <input type="checkbox" checked={selectedPaymentIds.includes(p.id)} onChange={() => togglePayment(p.id)} className="rounded" />
                      <div>
                        <p className="text-sm font-medium">{p.client ? `${p.client.firstName} ${p.client.lastName}` : "—"}</p>
                        <p className="text-xs text-gray-400">{p.channel} · {p.paymentDate ? formatDate(p.paymentDate) : formatDate(p.createdAt)}</p>
                      </div>
                    </div>
                    <span className="font-semibold text-green-700 text-sm">{formatCurrency(Number(p.amount))}</span>
                  </label>
                ))}
              </div>
              <div className="bg-blue-50 rounded-lg px-4 py-3 flex justify-between text-sm font-semibold text-blue-800">
                <span>{selectedPaymentIds.length} payments selected</span>
                <span>{formatCurrency(selectedTotal)}</span>
              </div>
            </>
          )}
          <div className="flex flex-col gap-1.5">
            <label className="text-sm font-medium text-gray-700">Notes (optional)</label>
            <textarea className="border rounded-lg px-3 py-2 text-sm resize-none h-20 focus:outline-none focus:ring-2 focus:ring-blue-500"
              value={notes} onChange={e => setNotes(e.target.value)} placeholder="Add any notes..." />
          </div>
          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={() => setShowSubmit(false)}>Cancel</Button>
            <Button onClick={() => submitRemittance.mutate()} isLoading={submitRemittance.isPending}
              disabled={selectedPaymentIds.length === 0}>
              Submit {selectedPaymentIds.length > 0 ? `(${formatCurrency(selectedTotal)})` : ""}
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}
