"use client";

import { useEffect } from "react";
import { useForm, type SubmitHandler, type Resolver } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { bankAccountSchema, type BankAccountInput } from "@/lib/validations/bank-account";
import { useCreateBankAccount, useUpdateBankAccount } from "@/hooks/use-bank-accounts";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import type { BankAccount } from "@prisma/client";

const ACCOUNT_TYPES = ["CHECKING", "SAVINGS", "CASH", "WALLET", "INVESTMENT", "OTHER"] as const;

const PRESET_COLORS = [
  "#10b981", "#3b82f6", "#f59e0b", "#ef4444",
  "#8b5cf6", "#ec4899", "#06b6d4", "#84cc16",
];

interface Props {
  open: boolean;
  onClose: () => void;
  existing?: BankAccount;
}

export function BankAccountDialog({ open, onClose, existing }: Props) {
  const create = useCreateBankAccount();
  const update = useUpdateBankAccount();
  const isEdit = !!existing;

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    reset,
    formState: { errors, isSubmitting },
  } = useForm<BankAccountInput>({
    resolver: zodResolver(bankAccountSchema) as Resolver<BankAccountInput>,
    defaultValues: {
      type: "CHECKING",
      balanceCents: 0,
      currency: "USD",
      includeInNetWorth: true,
      color: "#10b981",
    },
  });

  useEffect(() => {
    if (existing) {
      reset({
        name: existing.name,
        type: existing.type,
        balanceCents: existing.balanceCents,
        currency: existing.currency,
        institutionName: existing.institutionName ?? undefined,
        lastFourDigits: existing.lastFourDigits ?? undefined,
        color: existing.color ?? "#10b981",
        includeInNetWorth: existing.includeInNetWorth,
      });
    } else {
      reset({
        type: "CHECKING",
        balanceCents: 0,
        currency: "USD",
        includeInNetWorth: true,
        color: "#10b981",
      });
    }
  }, [existing, reset]);

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

  const selectedColor = watch("color");

  return (
    <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
      <DialogContent className="bg-slate-900 border-slate-700 text-white sm:max-w-md">
        <DialogHeader>
          <DialogTitle>{isEdit ? "Edit Account" : "Add Bank Account"}</DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
          <div className="space-y-1">
            <Label className="text-slate-300">Account Name *</Label>
            <Input
              {...register("name")}
              placeholder="e.g. Main Checking"
              className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
            />
            {errors.name && <p className="text-xs text-red-400">{errors.name.message}</p>}
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1">
              <Label className="text-slate-300">Type *</Label>
              <Select
                value={watch("type")}
                onValueChange={(v) => setValue("type", v as BankAccountInput["type"])}
              >
                <SelectTrigger className="bg-slate-800 border-slate-600 text-slate-200">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-slate-800 border-slate-600">
                  {ACCOUNT_TYPES.map((t) => (
                    <SelectItem key={t} value={t} className="text-slate-200 focus:bg-slate-700">
                      {t.charAt(0) + t.slice(1).toLowerCase()}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-1">
              <Label className="text-slate-300">Currency</Label>
              <Input
                {...register("currency")}
                placeholder="USD"
                maxLength={3}
                className="bg-slate-800 border-slate-600 text-white uppercase"
              />
            </div>
          </div>

          {!isEdit && (
            <div className="space-y-1">
              <Label className="text-slate-300">Opening Balance</Label>
              <Input
                type="number"
                step="0.01"
                placeholder="0.00"
                className="bg-slate-800 border-slate-600 text-white"
                onChange={(e) =>
                  setValue("balanceCents", Math.round(parseFloat(e.target.value || "0") * 100))
                }
                defaultValue={0}
              />
            </div>
          )}

          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1">
              <Label className="text-slate-300">Institution</Label>
              <Input
                {...register("institutionName")}
                placeholder="Bank name"
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
            </div>
            <div className="space-y-1">
              <Label className="text-slate-300">Last 4 digits</Label>
              <Input
                {...register("lastFourDigits")}
                placeholder="1234"
                maxLength={4}
                className="bg-slate-800 border-slate-600 text-white"
              />
            </div>
          </div>

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

          <DialogFooter>
            <Button
              type="button"
              variant="ghost"
              onClick={onClose}
              className="text-slate-400 hover:text-white"
            >
              Cancel
            </Button>
            <Button
              type="submit"
              disabled={isSubmitting}
              className="bg-emerald-600 hover:bg-emerald-500 text-white"
            >
              {isEdit ? "Save Changes" : "Add Account"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
