import { zodResolver } from "@hookform/resolvers/zod";
import { Controller, 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 { useTransferWallet, useWallets } from "@/lib/queries";
import type { Wallet } from "@/lib/api";

const transferSchema = z.object({
  toWalletId: z.number().positive("Seleccioná una billetera destino"),
  outgoingAmount: z.number().positive("El monto saliente debe ser mayor a 0"),
  incomingAmount: z.number().positive("El monto entrante debe ser mayor a 0"),
  description: z.string().max(255).optional(),
});

type TransferFormValues = z.infer<typeof transferSchema>;

interface TransferDialogProps {
  sourceWallet: Wallet;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function TransferDialog({
  sourceWallet,
  open,
  onOpenChange,
}: TransferDialogProps) {
  const { data: wallets } = useWallets();
  const transfer = useTransferWallet();

  const otherWallets =
    wallets?.filter((w) => w.id !== sourceWallet.id) ?? [];

  const {
    register,
    handleSubmit,
    control,
    formState: { errors, isSubmitting },
    reset,
  } = useForm<TransferFormValues>({
    resolver: zodResolver(transferSchema),
    defaultValues: {
      toWalletId: 0,
      outgoingAmount: 0,
      incomingAmount: 0,
      description: "",
    },
  });

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

  async function onSubmit(data: TransferFormValues) {
    await transfer.mutateAsync({
      fromWalletId: sourceWallet.id,
      toWalletId: data.toWalletId,
      outgoingAmount: data.outgoingAmount,
      incomingAmount: data.incomingAmount,
      description: data.description || undefined,
    });
    handleClose(false);
  }

  return (
    <ResponsiveDialog open={open} onOpenChange={handleClose}>
      <ResponsiveDialogContent>
        <ResponsiveDialogHeader>
          <ResponsiveDialogTitle>
            Transferir desde {sourceWallet.name}
          </ResponsiveDialogTitle>
        </ResponsiveDialogHeader>

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

        <form
          id="transfer-form"
          onSubmit={handleSubmit(onSubmit)}
          className="flex flex-col gap-4"
        >
          <div className="flex flex-col gap-1.5">
            <label className="text-sm font-medium">Billetera destino</label>
            <Controller
              control={control}
              name="toWalletId"
              render={({ field }) => (
                <Select
                  value={field.value ? String(field.value) : ""}
                  onValueChange={(v) => field.onChange(Number(v))}
                >
                  <SelectTrigger className="h-8">
                    <SelectValue placeholder="Seleccionar destino" />
                  </SelectTrigger>
                  <SelectContent>
                    {otherWallets.map((w) => (
                      <SelectItem key={w.id} value={String(w.id)}>
                        {w.name} ({w.currency})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              )}
            />
            {errors.toWalletId && (
              <span className="text-xs text-destructive">
                {errors.toWalletId.message}
              </span>
            )}
          </div>

          <div className="flex flex-col gap-1.5">
            <label
              htmlFor="transfer-outgoing"
              className="text-sm font-medium"
            >
              Monto saliente (de {sourceWallet.name})
            </label>
            <input
              id="transfer-outgoing"
              type="number"
              step="0.01"
              min="0"
              {...register("outgoingAmount", { valueAsNumber: true })}
              placeholder="1000"
              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.outgoingAmount && (
              <span className="text-xs text-destructive">
                {errors.outgoingAmount.message}
              </span>
            )}
          </div>

          <div className="flex flex-col gap-1.5">
            <label
              htmlFor="transfer-incoming"
              className="text-sm font-medium"
            >
              Monto entrante (en destino)
            </label>
            <input
              id="transfer-incoming"
              type="number"
              step="0.01"
              min="0"
              {...register("incomingAmount", { valueAsNumber: true })}
              placeholder="950"
              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.incomingAmount && (
              <span className="text-xs text-destructive">
                {errors.incomingAmount.message}
              </span>
            )}
            <span className="text-xs text-muted-foreground">
              Si hay comisiones o diferencia de cotización, el monto entrante
              puede ser menor al saliente.
            </span>
          </div>

          <div className="flex flex-col gap-1.5">
            <label htmlFor="transfer-desc" className="text-sm font-medium">
              Descripción (opcional)
            </label>
            <input
              id="transfer-desc"
              {...register("description")}
              placeholder="Ej: Transferencia a Binance"
              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="transfer-form" disabled={isSubmitting}>
            Transferir
          </Button>
        </ResponsiveDialogFooter>
      </ResponsiveDialogContent>
    </ResponsiveDialog>
  );
}
