"use client";

import { useEffect } from "react";
import { useForm, type SubmitHandler, type Resolver } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { creditCardSchema, type CreditCardInput } from "@/lib/validations/credit-card";
import { useCreateCreditCard, useUpdateCreditCard } from "@/hooks/use-credit-cards";
import type { CreditCard } from "@prisma/client";

const COLORS = [
  "#3b82f6", "#8b5cf6", "#ec4899", "#ef4444",
  "#f97316", "#eab308", "#10b981", "#06b6d4",
];

// Convert stored values to display values for form inputs
function toDisplay(card: CreditCard): CreditCardInput {
  return {
    name:                    card.name,
    lastFourDigits:          card.lastFourDigits ?? undefined,
    creditLimitCents:        card.creditLimitCents / 100,       // cents → dollars
    statementDayOfMonth:     card.statementDayOfMonth,
    paymentDueDayOffset:     card.paymentDueDayOffset,
    minimumPaymentPct:       card.minimumPaymentPct * 100,      // 0.02 → 2 (%)
    minimumPaymentFlatCents: card.minimumPaymentFlatCents / 100, // cents → dollars
    interestRateBps:         card.interestRateBps / 100,        // 2400 → 24 (%)
    currency:                card.currency,
    color:                   card.color ?? undefined,
  };
}

const CREATE_DEFAULTS: Partial<CreditCardInput> = {
  paymentDueDayOffset:     21,
  minimumPaymentPct:       2,    // 2%
  minimumPaymentFlatCents: 25,   // $25
  currency:                "USD",
  statementDayOfMonth:     1,
  interestRateBps:         24,   // 24% APR
  creditLimitCents:        0,
};

interface Props {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  existing?: CreditCard;
}

export function CreditCardDialog({ open, onOpenChange, existing }: Props) {
  const isEdit = !!existing;
  const create = useCreateCreditCard();
  const update = useUpdateCreditCard();

  const form = useForm<CreditCardInput>({
    resolver: zodResolver(creditCardSchema) as Resolver<CreditCardInput>,
    defaultValues: existing ? toDisplay(existing) : CREATE_DEFAULTS,
  });

  // Reset form whenever the dialog opens or switches between add/edit
  useEffect(() => {
    if (!open) return;
    form.reset(existing ? toDisplay(existing) : CREATE_DEFAULTS);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, existing?.id]);

  const selectedColor = form.watch("color");

  const onSubmit: SubmitHandler<CreditCardInput> = async (data) => {
    if (isEdit) {
      await update.mutateAsync({ id: existing.id, data });
    } else {
      await create.mutateAsync(data);
    }
    onOpenChange(false);
  };

  const isPending = create.isPending || update.isPending;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="bg-slate-900 border-slate-700 text-white max-w-lg">
        <DialogHeader>
          <DialogTitle>{isEdit ? "Edit Credit Card" : "Add Credit Card"}</DialogTitle>
        </DialogHeader>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4 mt-2">
          <div className="space-y-1">
            <Label className="text-slate-300">Card Name</Label>
            <Input
              {...form.register("name")}
              placeholder="e.g. Chase Sapphire"
              className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
            />
            {form.formState.errors.name && (
              <p className="text-red-400 text-xs">{form.formState.errors.name.message}</p>
            )}
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1">
              <Label className="text-slate-300">Last 4 Digits</Label>
              <Input
                {...form.register("lastFourDigits")}
                placeholder="1234"
                maxLength={4}
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
            </div>
            <div className="space-y-1">
              <Label className="text-slate-300">Currency</Label>
              <select
                {...form.register("currency")}
                className="w-full h-9 rounded-lg border border-slate-600 bg-slate-800 text-slate-200 px-3 text-sm focus:outline-none focus:ring-1 focus:ring-ring"
              >
                {["USD", "EUR", "GBP", "LKR", "INR", "SGD", "AUD", "CAD"].map((c) => (
                  <option key={c} value={c}>{c}</option>
                ))}
              </select>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1">
              <Label className="text-slate-300">Credit Limit</Label>
              <Input
                type="number"
                step="0.01"
                min="0"
                {...form.register("creditLimitCents", {
                  setValueAs: (v) => Math.round(parseFloat(v || "0") * 100),
                })}
                placeholder="5000.00"
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
              {form.formState.errors.creditLimitCents && (
                <p className="text-red-400 text-xs">{form.formState.errors.creditLimitCents.message}</p>
              )}
            </div>
            <div className="space-y-1">
              <Label className="text-slate-300">Annual Rate (%)</Label>
              <Input
                type="number"
                step="0.01"
                min="0"
                {...form.register("interestRateBps", {
                  setValueAs: (v) => Math.round(parseFloat(v || "0") * 100),
                })}
                placeholder="24.00"
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1">
              <Label className="text-slate-300">Statement Day</Label>
              <Input
                type="number"
                min={1}
                max={31}
                {...form.register("statementDayOfMonth", { valueAsNumber: true })}
                placeholder="1"
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
            </div>
            <div className="space-y-1">
              <Label className="text-slate-300">Payment Due (days after)</Label>
              <Input
                type="number"
                min={1}
                max={60}
                {...form.register("paymentDueDayOffset", { valueAsNumber: true })}
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1">
              <Label className="text-slate-300">Min Payment %</Label>
              <Input
                type="number"
                step="0.01"
                min={0}
                max={100}
                {...form.register("minimumPaymentPct", {
                  setValueAs: (v) => parseFloat(v || "0") / 100,
                })}
                placeholder="2.00"
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
            </div>
            <div className="space-y-1">
              <Label className="text-slate-300">Min Payment Flat</Label>
              <Input
                type="number"
                step="0.01"
                min={0}
                {...form.register("minimumPaymentFlatCents", {
                  setValueAs: (v) => Math.round(parseFloat(v || "0") * 100),
                })}
                placeholder="25.00"
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label className="text-slate-300">Card Color</Label>
            <div className="flex gap-2 flex-wrap">
              {COLORS.map((c) => (
                <button
                  key={c}
                  type="button"
                  onClick={() => form.setValue("color", c)}
                  className="w-7 h-7 rounded-full border-2 transition-all"
                  style={{
                    backgroundColor: c,
                    borderColor: selectedColor === c ? "white" : "transparent",
                  }}
                />
              ))}
            </div>
          </div>

          <div className="flex gap-3 pt-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              className="flex-1 border-slate-600 text-slate-300 hover:bg-slate-800"
            >
              Cancel
            </Button>
            <Button
              type="submit"
              disabled={isPending}
              className="flex-1 bg-emerald-600 hover:bg-emerald-500 text-white"
            >
              {isPending ? "Saving…" : isEdit ? "Update Card" : "Add Card"}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
