"use client";

import { useEffect, useRef, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Plus, Landmark, CheckCircle, Building2, ArrowLeftRight, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { LoanDialog } from "@/components/loans/LoanDialog";
import { TransactionDialog } from "@/components/transactions/TransactionDialog";
import {
  useLoans,
  useDeleteLoan,
  useMarkPaymentPaid,
  useFixLoanHistory,
  type LoanWithSchedule,
} from "@/hooks/use-loans";
import { formatCents, formatDate } from "@/lib/utils/format";

const LOAN_TYPE_LABELS: Record<string, string> = {
  PERSONAL: "Personal",
  HOME_MORTGAGE: "Mortgage",
  AUTO: "Auto",
  STUDENT: "Student",
  BUSINESS: "Business",
  OTHER: "Other",
};

function LoanCard({
  loan,
  onTransfer,
}: {
  loan: LoanWithSchedule;
  onTransfer: (accountId: string) => void;
}) {
  const deleteLoan = useDeleteLoan();
  const markPaid   = useMarkPaymentPaid();

  const totalInstallments = loan._count.schedule;
  const paid              = loan.paidInstallments;
  const progress          = totalInstallments > 0 ? (paid / totalInstallments) * 100 : 0;

  const nextPayment = loan.schedule[0];

  return (
    <Card className="bg-slate-800/50 border-slate-700/50">
      <CardContent className="p-4 space-y-3">
        {/* Header */}
        <div className="flex items-start justify-between">
          <div>
            <div className="flex items-center gap-2">
              <Landmark className="h-4 w-4 text-slate-400" />
              <span className="font-semibold text-white">{loan.name}</span>
              <Badge className="bg-slate-700 text-slate-300 border-slate-600 text-xs">
                {LOAN_TYPE_LABELS[loan.type]}
              </Badge>
            </div>
            {loan.lenderName && (
              <p className="text-xs text-slate-500 mt-0.5">{loan.lenderName}</p>
            )}
          </div>
          <button
            onClick={() => deleteLoan.mutate(loan.id)}
            className="text-xs text-slate-600 hover:text-red-400 transition-colors"
          >
            Close
          </button>
        </div>

        {/* Linked account chip */}
        {loan.bankAccount && (
          <div className="flex items-center gap-1.5">
            <Building2 className="h-3 w-3 text-slate-500" />
            <span className="text-xs text-slate-500">Linked to</span>
            <span
              className="text-xs font-semibold px-2 py-0.5 rounded-full"
              style={{
                color:           loan.bankAccount.color ?? "#a5b4fc",
                backgroundColor: `${loan.bankAccount.color ?? "#6366f1"}20`,
              }}
            >
              {loan.bankAccount.name}
            </span>
            <button
              onClick={() => onTransfer(loan.bankAccount!.id)}
              className="ml-auto flex items-center gap-1 text-[10px] text-blue-400 hover:text-blue-300 transition-colors"
            >
              <ArrowLeftRight className="h-2.5 w-2.5" />
              Transfer funds
            </button>
          </div>
        )}

        {/* Stats */}
        <div className="grid grid-cols-3 gap-3 text-center">
          <div className="bg-slate-900/50 rounded-lg p-2">
            <div className="text-xs text-slate-400">Outstanding</div>
            <div className="text-sm font-semibold text-white mt-0.5">
              {formatCents(loan.outstandingCents)}
            </div>
          </div>
          <div className="bg-slate-900/50 rounded-lg p-2">
            <div className="text-xs text-slate-400">Principal</div>
            <div className="text-sm font-semibold text-slate-300 mt-0.5">
              {formatCents(loan.principalCents)}
            </div>
          </div>
          <div className="bg-slate-900/50 rounded-lg p-2">
            <div className="text-xs text-slate-400">Rate</div>
            <div className="text-sm font-semibold text-amber-400 mt-0.5">
              {(loan.annualRateBps / 100).toFixed(2)}%
            </div>
          </div>
        </div>

        {/* Progress */}
        <div className="space-y-1">
          <div className="flex justify-between text-xs text-slate-400">
            <span>{paid} of {totalInstallments} EMIs paid</span>
            <span>{progress.toFixed(0)}%</span>
          </div>
          <Progress value={progress} className="h-1.5 bg-slate-700" />
        </div>

        {/* Next EMI — quick pay */}
        {nextPayment ? (
          <div className="flex items-center justify-between bg-slate-900/40 rounded-lg px-3 py-2">
            <div>
              <p className="text-xs text-slate-400">Next EMI · {formatDate(nextPayment.dueDate)}</p>
              {loan.bankAccount && (
                <p className="text-[10px] text-slate-600 mt-0.5">
                  debits {loan.bankAccount.name}
                </p>
              )}
            </div>
            <div className="flex items-center gap-2">
              <span className="text-white font-medium text-sm">{formatCents(nextPayment.emiCents)}</span>
              <button
                onClick={() =>
                  markPaid.mutate({ loanId: loan.id, paymentId: nextPayment.id, amountCents: nextPayment.emiCents })
                }
                disabled={markPaid.isPending}
                className="px-2.5 py-1 text-[11px] font-semibold rounded-lg bg-emerald-600/20 text-emerald-400 border border-emerald-600/30 hover:bg-emerald-600/30 transition-colors disabled:opacity-50"
              >
                {markPaid.isPending ? "…" : "Pay EMI"}
              </button>
            </div>
          </div>
        ) : (
          <div className="flex items-center gap-2 bg-emerald-900/20 rounded-lg px-3 py-2">
            <CheckCircle className="h-4 w-4 text-emerald-500" />
            <span className="text-xs text-emerald-400 font-medium">All EMIs paid — loan complete!</span>
          </div>
        )}
      </CardContent>
    </Card>
  );
}

function useCleanupEmi() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: async () => {
      const res = await fetch("/api/loans/cleanup-emi", { method: "DELETE" });
      if (!res.ok) throw new Error("Cleanup failed");
      return res.json() as Promise<{ deleted: number; totalReversedCents: number }>;
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["bank-accounts"] });
      qc.invalidateQueries({ queryKey: ["transactions"] });
      qc.invalidateQueries({ queryKey: ["dashboard"] });
    },
  });
}

export default function LoansPage() {
  const { data: loans, isLoading } = useLoans();
  const [dialogOpen,    setDialogOpen]    = useState(false);
  const [transferOpen,  setTransferOpen]  = useState(false);
  const [transferAccId, setTransferAccId] = useState<string | undefined>();
  const [cleanupDone,   setCleanupDone]   = useState(false);

  const fixHistory   = useFixLoanHistory();
  const cleanupEmi   = useCleanupEmi();
  const fixedIds     = useRef(new Set<string>());

  const totalOutstanding = loans?.reduce((s, l) => s + l.outstandingCents, 0) ?? 0;

  // Auto-fix historical unpaid installments for existing loans
  useEffect(() => {
    if (!loans) return;
    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);

    for (const loan of loans) {
      if (fixedIds.current.has(loan.id)) continue;
      const next = loan.schedule[0];
      if (next && new Date(next.dueDate) < todayStart) {
        fixedIds.current.add(loan.id);
        fixHistory.mutate(loan.id);
      }
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [loans]);

  function handleTransfer(accountId: string) {
    setTransferAccId(accountId);
    setTransferOpen(true);
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Loans</h1>
          {loans && loans.length > 0 && (
            <p className="text-slate-400 text-sm mt-1">
              {formatCents(totalOutstanding)} total outstanding
            </p>
          )}
        </div>
        <div className="flex gap-2 flex-wrap">
          {!cleanupDone && (
            <Button
              onClick={async () => {
                const result = await cleanupEmi.mutateAsync();
                if (result.deleted > 0) setCleanupDone(true);
              }}
              disabled={cleanupEmi.isPending}
              variant="outline"
              className="border-rose-500/40 text-rose-300 hover:bg-rose-500/10 text-xs"
              title="Remove phantom EMI expense transactions created by manually paying historical installments"
            >
              <Trash2 className="h-3.5 w-3.5 mr-1.5" />
              {cleanupEmi.isPending ? "Fixing…" : cleanupEmi.isSuccess ? `Fixed ${cleanupEmi.data?.deleted} txns` : "Fix EMI data"}
            </Button>
          )}
          <Button
            onClick={() => { setTransferAccId(undefined); setTransferOpen(true); }}
            variant="outline"
            className="border-blue-500/40 text-blue-300 hover:bg-blue-500/10"
          >
            <ArrowLeftRight className="h-4 w-4 mr-2" />
            Transfer
          </Button>
          <Button
            onClick={() => setDialogOpen(true)}
            className="bg-emerald-600 hover:bg-emerald-500 text-white"
          >
            <Plus className="h-4 w-4 mr-2" />
            Add Loan
          </Button>
        </div>
      </div>

      {isLoading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {Array.from({ length: 2 }).map((_, i) => (
            <div key={i} className="h-52 bg-slate-800/30 rounded-xl animate-pulse" />
          ))}
        </div>
      ) : !loans || loans.length === 0 ? (
        <Card className="bg-slate-800/30 border-slate-700/50 border-dashed">
          <CardContent className="flex flex-col items-center justify-center py-16 text-center">
            <Landmark className="h-10 w-10 text-slate-600 mb-3" />
            <p className="text-slate-400 font-medium">No active loans</p>
            <p className="text-slate-500 text-sm mt-1">
              Add a loan and link it to a bank account — EMI payments will automatically debit it
            </p>
            <Button
              onClick={() => setDialogOpen(true)}
              className="mt-4 bg-emerald-600 hover:bg-emerald-500 text-white"
            >
              <Plus className="h-4 w-4 mr-2" />
              Add Loan
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {loans.map((loan) => (
            <LoanCard key={loan.id} loan={loan} onTransfer={handleTransfer} />
          ))}
        </div>
      )}

      <LoanDialog open={dialogOpen} onOpenChange={setDialogOpen} />

      <TransactionDialog
        open={transferOpen}
        onClose={() => setTransferOpen(false)}
        defaultType="TRANSFER"
        defaultFromAccountId={transferAccId}
      />
    </div>
  );
}
