"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
// import { useToast } from "@/hooks/use-toast"; // Fixed import path
import { CreditCard, Banknote } from "lucide-react";
import { DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";

const paymentMethodSchema = z.object({
  type: z.enum(["credit", "paypal", "bank"]),
  // Credit card fields
  cardNumber: z.string().optional().refine(value => {
    if (value === undefined) return true;
    return /^\d{16}$/.test(value.replace(/\s/g, ''));
  }, { message: "Card number must be 16 digits" }),
  cardholderName: z.string().optional(),
  expiryDate: z.string().optional().refine(value => {
    if (value === undefined) return true;
    return /^(0[1-9]|1[0-2])\/\d{2}$/.test(value);
  }, { message: "Expiry date must be in MM/YY format" }),
  cvv: z.string().optional().refine(value => {
    if (value === undefined) return true;
    return /^\d{3,4}$/.test(value);
  }, { message: "CVV must be 3 or 4 digits" }),
  // PayPal fields
  email: z.string().email().optional(),
  // Bank account fields
  accountNumber: z.string().optional(),
  routingNumber: z.string().optional(),
  accountName: z.string().optional(),
  makeDefault: z.boolean().default(false),
});

type PaymentMethodFormValues = z.infer<typeof paymentMethodSchema>;

interface AddPaymentMethodFormProps {
  onSuccess: () => void;
}

export function AddPaymentMethodForm({ onSuccess }: AddPaymentMethodFormProps) {
  // const { toast } = useToast();
  const form = useForm<PaymentMethodFormValues>({
    resolver: zodResolver(paymentMethodSchema),
    defaultValues: {
      type: "credit",
      makeDefault: false,
    },
  });

  const watchType = form.watch("type");

  function onSubmit(data: PaymentMethodFormValues) {
    // toast({
    //   title: "Payment method added",
    //   description: "Your new payment method has been added successfully."
    // });
    console.log(data);
    form.reset();
    onSuccess();
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
        <FormField
          control={form.control}
          name="type"
          render={({ field }) => (
            <FormItem className="space-y-3">
              <FormLabel>Payment Method Type</FormLabel>
              <FormControl>
                <RadioGroup
                  onValueChange={field.onChange}
                  defaultValue={field.value}
                  className="grid grid-cols-3 gap-4"
                >
                  <Label
                    htmlFor="credit"
                    className="flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary"
                  >
                    <RadioGroupItem value="credit" id="credit" className="sr-only" />
                    <CreditCard className="mb-3 h-6 w-6" />
                    <span className="text-sm font-medium">Credit Card</span>
                  </Label>
                  <Label
                    htmlFor="paypal"
                    className="flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary"
                  >
                    <RadioGroupItem value="paypal" id="paypal" className="sr-only" />
                    <CreditCard className="mb-3 h-6 w-6" />
                    <span className="text-sm font-medium">PayPal</span>
                  </Label>
                  <Label
                    htmlFor="bank"
                    className="flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary"
                  >
                    <RadioGroupItem value="bank" id="bank" className="sr-only" />
                    <Banknote className="mb-3 h-6 w-6" />
                    <span className="text-sm font-medium">Bank Account</span>
                  </Label>
                </RadioGroup>
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {watchType === "credit" && (
          <div className="space-y-4">
            <FormField
              control={form.control}
              name="cardNumber"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Card Number</FormLabel>
                  <FormControl>
                    <Input placeholder="4242 4242 4242 4242" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="cardholderName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Cardholder Name</FormLabel>
                  <FormControl>
                    <Input placeholder="John Doe" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="expiryDate"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Expiry Date</FormLabel>
                    <FormControl>
                      <Input placeholder="MM/YY" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="cvv"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>CVV</FormLabel>
                    <FormControl>
                      <Input placeholder="123" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </div>
        )}

        {watchType === "paypal" && (
          <FormField
            control={form.control}
            name="email"
            render={({ field }) => (
              <FormItem>
                <FormLabel>PayPal Email</FormLabel>
                <FormControl>
                  <Input type="email" placeholder="your.email@example.com" {...field} />
                </FormControl>
                <FormDescription>
                  Enter the email associated with your PayPal account.
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        )}

        {watchType === "bank" && (
          <div className="space-y-4">
            <FormField
              control={form.control}
              name="accountName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Account Name</FormLabel>
                  <FormControl>
                    <Input placeholder="John Doe" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="accountNumber"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Account Number</FormLabel>
                  <FormControl>
                    <Input placeholder="000123456789" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="routingNumber"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Routing Number</FormLabel>
                  <FormControl>
                    <Input placeholder="123456789" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
        )}

        <FormField
          control={form.control}
          name="makeDefault"
          render={({ field }) => (
            <FormItem className="flex flex-row items-start space-x-3 space-y-0">
              <FormControl>
                <input
                  type="checkbox"
                  checked={field.value}
                  onChange={field.onChange}
                  className="h-4 w-4 rounded border-gray-300"
                />
              </FormControl>
              <div className="space-y-1 leading-none">
                <FormLabel>Set as default payment method</FormLabel>
                <FormDescription>
                  This will be used as your primary payment method.
                </FormDescription>
              </div>
            </FormItem>
          )}
        />

        <DialogFooter>
          <Button type="submit" className="text-white">Add Payment Method</Button>
        </DialogFooter>
      </form>
    </Form>
  );
}
