"use client";

import { AlertCircle, CheckCircle2, DollarSign, Loader2, X } from "lucide-react";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { currency } from "@/lib/utils";

interface ClearEntryModalProps {
  isOpen: boolean;
  onClose: () => void;
  onConfirm: (amountPaid: number, paidAt: string, newDueDate?: string) => Promise<void>;
  entry: { id: string; description: string; amount: number } | null;
  type: "RECEIVABLE" | "PAYABLE";
  isSaving?: boolean;
}

export function ClearEntryModal({
  isOpen,
  onClose,
  onConfirm,
  entry,
  type,
  isSaving = false,
}: ClearEntryModalProps) {
  const today = new Date().toISOString().split("T")[0];

  const [clearType, setClearType] = useState<"TOTAL" | "PARTIAL">("TOTAL");
  const [paidAt, setPaidAt] = useState(today);
  const [newDueDate, setNewDueDate] = useState("");
  const [amountPaidDisplay, setAmountPaidDisplay] = useState("");
  const [amountPaidValue, setAmountPaidValue] = useState(0);
  const [errorMsg, setErrorMsg] = useState("");

  const formatCurrency = (value: string) => {
    const clean = value.replace(/\D/g, "");
    if (!clean) return "";
    const num = parseInt(clean, 10) / 100;
    return new Intl.NumberFormat("pt-BR", {
      style: "currency",
      currency: "BRL",
    }).format(num);
  };

  const parseCurrencyToNumber = (value: string): number => {
    const clean = value.replace(/\D/g, "");
    if (!clean) return 0;
    return parseInt(clean, 10) / 100;
  };

  useEffect(() => {
    if (entry && isOpen) {
      const amt = Number(entry.amount) || 0;
      setClearType("TOTAL");
      setPaidAt(today);
      setNewDueDate("");
      setAmountPaidValue(amt);
      setAmountPaidDisplay(
        new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(amt)
      );
      setErrorMsg("");
    }
  }, [entry, isOpen, today]);

  const handleAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const formatted = formatCurrency(e.target.value);
    const parsed = parseCurrencyToNumber(formatted);
    setAmountPaidDisplay(formatted);
    setAmountPaidValue(parsed);

    if (entry && parsed >= Number(entry.amount)) {
      setErrorMsg(`Para baixa parcial, o valor deve ser menor que o total (${currency(Number(entry.amount))}).`);
    } else if (parsed <= 0) {
      setErrorMsg("O valor da baixa deve ser maior que R$ 0,00.");
    } else {
      setErrorMsg("");
    }
  };

  const handleClearTypeChange = (mode: "TOTAL" | "PARTIAL") => {
    setClearType(mode);
    setErrorMsg("");
    setNewDueDate("");
    if (entry) {
      const amt = Number(entry.amount) || 0;
      if (mode === "TOTAL") {
        setAmountPaidValue(amt);
        setAmountPaidDisplay(
          new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(amt)
        );
      } else {
        const half = amt / 2;
        setAmountPaidValue(half);
        setAmountPaidDisplay(
          new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(half)
        );
      }
    }
  };

  const handleFormSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!entry) return;

    const limit = Number(entry.amount);
    if (clearType === "PARTIAL") {
      if (amountPaidValue <= 0) {
        setErrorMsg("O valor da baixa deve ser maior que R$ 0,00.");
        return;
      }
      if (amountPaidValue >= limit) {
        setErrorMsg(`Para baixa parcial, o valor deve ser menor que o total (${currency(limit)}).`);
        return;
      }
      if (!newDueDate) {
        setErrorMsg("Informe a nova data de vencimento para o saldo restante.");
        return;
      }
    }

    await onConfirm(
      clearType === "TOTAL" ? limit : amountPaidValue,
      paidAt,
      clearType === "PARTIAL" ? newDueDate : undefined
    );
    onClose();
  };

  if (!isOpen || !entry) return null;

  const isReceivable = type === "RECEIVABLE";
  const remainingAmount = clearType === "PARTIAL" ? Math.max(0, Number(entry.amount) - amountPaidValue) : 0;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-xs transition-all">
      <Card className="w-full max-w-md max-h-[90vh] overflow-y-auto p-6 shadow-2xl">
        <div className="flex items-center justify-between border-b pb-4">
          <div>
            <h2 className="text-lg font-bold flex items-center gap-2">
              <DollarSign className="h-5 w-5 text-emerald-600 dark:text-emerald-400" />
              {isReceivable ? "Dar Baixa em Recebimento" : "Dar Baixa em Pagamento"}
            </h2>
            <p className="text-xs text-muted-foreground">
              {isReceivable
                ? "Confirme a liquidação total ou parcial deste contas a receber."
                : "Confirme a liquidação total ou parcial deste contas a pagar."}
            </p>
          </div>
          <Button variant="ghost" size="icon" onClick={onClose}>
            <X className="h-5 w-5" />
          </Button>
        </div>

        <form onSubmit={handleFormSubmit} className="mt-5 space-y-4">
          <div className="rounded-lg bg-muted/40 p-3.5 border text-xs space-y-1">
            <p className="text-muted-foreground uppercase font-bold text-[10px] tracking-wider">
              Título Selecionado
            </p>
            <p className="font-bold text-foreground truncate">{entry.description}</p>
            <p className="text-muted-foreground flex justify-between pt-1">
              <span>Valor Atual:</span>
              <span className="font-bold text-foreground text-sm">{currency(Number(entry.amount))}</span>
            </p>
          </div>

          <div>
            <label className="mb-1 block text-xs font-semibold text-muted-foreground uppercase tracking-wider">
              Tipo de Baixa
            </label>
            <div className="grid grid-cols-2 gap-2 mt-1">
              <button
                type="button"
                onClick={() => handleClearTypeChange("TOTAL")}
                className={`py-2 px-3 text-xs font-bold border rounded-lg transition-all ${
                  clearType === "TOTAL"
                    ? "bg-primary/10 border-primary text-primary"
                    : "bg-background hover:bg-muted/40 text-muted-foreground"
                }`}
              >
                Baixa Total (100%)
              </button>
              <button
                type="button"
                onClick={() => handleClearTypeChange("PARTIAL")}
                className={`py-2 px-3 text-xs font-bold border rounded-lg transition-all ${
                  clearType === "PARTIAL"
                    ? "bg-primary/10 border-primary text-primary"
                    : "bg-background hover:bg-muted/40 text-muted-foreground"
                }`}
              >
                Baixa Parcial
              </button>
            </div>
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <div>
              <label className="mb-1 block text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                Valor da Baixa (R$)
              </label>
              <Input
                type="text"
                value={amountPaidDisplay}
                onChange={handleAmountChange}
                disabled={clearType === "TOTAL"}
                className={`font-bold ${clearType === "TOTAL" ? "bg-muted" : ""}`}
              />
            </div>

            <div>
              <label className="mb-1 block text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                Data do Pagamento
              </label>
              <Input
                type="date"
                value={paidAt}
                onChange={(e) => setPaidAt(e.target.value)}
                required
              />
            </div>
          </div>

          {/* Saldo restante e nova data de vencimento — visível apenas na baixa parcial */}
          {clearType === "PARTIAL" && (
            <div className="rounded-lg border border-amber-300/60 bg-amber-50/60 dark:bg-amber-950/30 dark:border-amber-700/40 p-3.5 space-y-3">
              <div className="flex items-center gap-2 text-amber-700 dark:text-amber-400">
                <AlertCircle className="h-4 w-4 shrink-0" />
                <p className="text-xs font-semibold">Saldo restante após a baixa parcial</p>
              </div>

              <div className="flex items-center justify-between">
                <span className="text-xs text-muted-foreground">Valor que volta ao financeiro:</span>
                <span className="text-base font-extrabold text-amber-700 dark:text-amber-400">
                  {currency(remainingAmount)}
                </span>
              </div>

              <div>
                <label className="mb-1 block text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                  Nova Data de Vencimento <span className="text-rose-500">*</span>
                </label>
                <Input
                  type="date"
                  value={newDueDate}
                  onChange={(e) => {
                    setNewDueDate(e.target.value);
                    if (errorMsg === "Informe a nova data de vencimento para o saldo restante.") {
                      setErrorMsg("");
                    }
                  }}
                  min={today}
                  required={clearType === "PARTIAL"}
                  className="font-medium"
                />
                <p className="mt-1 text-[10px] text-muted-foreground">
                  O saldo de {currency(remainingAmount)} será mantido com esta nova data de vencimento.
                </p>
              </div>
            </div>
          )}

          {errorMsg && (
            <p className="text-xs font-medium text-rose-500 bg-rose-500/10 p-2 rounded-md">
              {errorMsg}
            </p>
          )}

          <div className="flex items-center justify-end gap-2 border-t pt-4">
            <Button type="button" variant="secondary" onClick={onClose}>
              Cancelar
            </Button>
            <Button type="submit" disabled={isSaving || !!errorMsg}>
              {isSaving && <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />}
              <CheckCircle2 className="mr-1.5 h-4 w-4 text-emerald-500" />
              Confirmar Baixa
            </Button>
          </div>
        </form>
      </Card>
    </div>
  );
}

