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 { useUpdateWallet } from "@/lib/queries";
import type { Wallet } from "@/lib/api";

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

type EditWalletFormValues = z.infer<typeof editWalletSchema>;

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

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

export function EditWalletDialog({
  wallet,
  open,
  onOpenChange,
}: EditWalletDialogProps) {
  const updateWallet = useUpdateWallet();

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset,
    setValue,
    watch,
  } = useForm<EditWalletFormValues>({
    resolver: zodResolver(editWalletSchema),
    defaultValues: { name: wallet.name, currency: wallet.currency },
  });

  const currency = watch("currency");

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

  async function onSubmit(data: EditWalletFormValues) {
    await updateWallet.mutateAsync({ id: wallet.id, data });
    handleClose(false);
  }

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

        <form
          id="edit-wallet-form"
          onSubmit={handleSubmit(onSubmit)}
          className="flex flex-col gap-4"
        >
          <div className="flex flex-col gap-1.5">
            <label htmlFor="edit-name" className="text-sm font-medium">
              Nombre
            </label>
            <input
              id="edit-name"
              {...register("name")}
              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="edit-currency" className="text-sm font-medium">
              Moneda
            </label>
            <Select
              value={currency}
              onValueChange={(v) => setValue("currency", v)}
            >
              <SelectTrigger className="h-8">
                <SelectValue />
              </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>
        </form>

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