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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useCreateWallet } from "@/lib/queries";

const createWalletSchema = z.object({
  name: z.string().min(1, "El nombre es obligatorio").max(100),
  currency: z.string().min(1, "La moneda es obligatoria"),
  initialBalance: z.number().nonnegative(),
});

type CreateWalletFormValues = z.infer<typeof createWalletSchema>;

interface CreateWalletDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

const commonCurrencies = ["ARS", "USD", "USDC", "EUR", "BRL", "USDT"];

export function CreateWalletDialog({
  open,
  onOpenChange,
}: CreateWalletDialogProps) {
  const createWallet = useCreateWallet();

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset,
    setValue,
    watch,
  } = useForm<CreateWalletFormValues>({
    resolver: zodResolver(createWalletSchema),
    defaultValues: { name: "", currency: "", initialBalance: 0 },
  });

  const currency = watch("currency");

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

  async function onSubmit(data: CreateWalletFormValues) {
    await createWallet.mutateAsync({
      name: data.name,
      currency: data.currency,
      initialBalance: data.initialBalance,
    });
    handleClose(false);
  }

  return (
    <ResponsiveDialog open={open} onOpenChange={handleClose}>
      <ResponsiveDialogContent>
        <ResponsiveDialogHeader>
          <ResponsiveDialogTitle>Nueva billetera</ResponsiveDialogTitle>
        </ResponsiveDialogHeader>

        <form
          id="create-wallet-form"
          onSubmit={handleSubmit(onSubmit)}
          className="flex flex-col gap-4"
        >
          <div className="flex flex-col gap-1.5">
            <label htmlFor="name" className="text-sm font-medium">
              Nombre
            </label>
            <input
              id="name"
              {...register("name")}
              placeholder="Ej: Mercado Pago"
              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.name && (
              <span className="text-xs text-destructive">
                {errors.name.message}
              </span>
            )}
          </div>

          <div className="flex flex-col gap-1.5">
            <label htmlFor="currency" className="text-sm font-medium">
              Moneda
            </label>
            <Select
              value={currency}
              onValueChange={(v) => setValue("currency", v)}
            >
              <SelectTrigger className="h-8">
                <SelectValue placeholder="Seleccionar moneda" />
              </SelectTrigger>
              <SelectContent>
                {commonCurrencies.map((c) => (
                  <SelectItem key={c} value={c}>
                    {c}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {errors.currency && (
              <span className="text-xs text-destructive">
                {errors.currency.message}
              </span>
            )}
          </div>

          <div className="flex flex-col gap-1.5">
            <label htmlFor="initialBalance" className="text-sm font-medium">
              Saldo inicial
            </label>
            <input
              id="initialBalance"
              type="number"
              step="0.01"
              min="0"
              {...register("initialBalance", { valueAsNumber: true })}
              placeholder="0"
              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.initialBalance && (
              <span className="text-xs text-destructive">
                {errors.initialBalance.message}
              </span>
            )}
          </div>
        </form>

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