import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import {
  ResponsiveDialog,
  ResponsiveDialogContent,
  ResponsiveDialogFooter,
  ResponsiveDialogHeader,
  ResponsiveDialogTitle,
} from "@/components/ui/responsive-dialog";
import { useAdjustBalance } from "@/lib/queries";
import type { Wallet } from "@/lib/api";

const adjustSchema = z.object({
  newBalance: z.number().min(0, "El saldo no puede ser negativo"),
  description: z.string().max(255).optional(),
});

type AdjustFormValues = z.infer<typeof adjustSchema>;

interface AdjustBalanceDialogProps {
  wallet: Wallet;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function AdjustBalanceDialog({
  wallet,
  open,
  onOpenChange,
}: AdjustBalanceDialogProps) {
  const adjust = useAdjustBalance();

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset,
  } = useForm<AdjustFormValues>({
    resolver: zodResolver(adjustSchema),
    defaultValues: { newBalance: wallet.balance, description: "" },
  });

  function handleClose(open: boolean) {
    onOpenChange(open);
    if (!open) reset();
  }

  async function onSubmit(data: AdjustFormValues) {
    await adjust.mutateAsync({
      id: wallet.id,
      data: {
        newBalance: data.newBalance,
        description: data.description || undefined,
      },
    });
    handleClose(false);
  }

  return (
    <ResponsiveDialog open={open} onOpenChange={handleClose}>
      <ResponsiveDialogContent>
        <ResponsiveDialogHeader>
          <ResponsiveDialogTitle>
            Ajustar saldo de {wallet.name}
          </ResponsiveDialogTitle>
        </ResponsiveDialogHeader>

        <p className="text-sm text-muted-foreground">
          Saldo actual: {wallet.balance}
        </p>

        <form
          id="adjust-form"
          onSubmit={handleSubmit(onSubmit)}
          className="flex flex-col gap-4"
        >
          <div className="flex flex-col gap-1.5">
            <label htmlFor="adjust-balance" className="text-sm font-medium">
              Nuevo saldo
            </label>
            <input
              id="adjust-balance"
              type="number"
              step="0.01"
              min="0"
              {...register("newBalance", { valueAsNumber: true })}
              className="h-8 rounded-lg border border-input bg-background px-2.5 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50"
            />
            {errors.newBalance && (
              <span className="text-xs text-destructive">
                {errors.newBalance.message}
              </span>
            )}
          </div>

          <div className="flex flex-col gap-1.5">
            <label htmlFor="adjust-desc" className="text-sm font-medium">
              Motivo (opcional)
            </label>
            <input
              id="adjust-desc"
              {...register("description")}
              placeholder="Ej: Corrección"
              className="h-8 rounded-lg border border-input bg-background px-2.5 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50"
            />
            {errors.description && (
              <span className="text-xs text-destructive">
                {errors.description.message}
              </span>
            )}
          </div>
        </form>

        <ResponsiveDialogFooter>
          <Button
            variant="outline"
            onClick={() => handleClose(false)}
            disabled={isSubmitting}
          >
            Cancelar
          </Button>
          <Button type="submit" form="adjust-form" disabled={isSubmitting}>
            Ajustar
          </Button>
        </ResponsiveDialogFooter>
      </ResponsiveDialogContent>
    </ResponsiveDialog>
  );
}
