'use client';
import React, { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { useRouter } from 'next/navigation';
import { useGlobalContext } from '@/context/Provider';
import apis from '@/utils/apis';
import CountryPickerModal from '@/components/countrycode/page';
import countries from '@/utils/CountryCode.json';

// Form validation schema - Only for India fields
const formSchema = z.object({
  name: z.string().min(1, 'Name is required'),
  accountNumber: z
    .string()
    .min(1, 'Account number is required')
    .regex(/^\d+$/, 'Must contain only numbers'),
  ifscCode: z.string().min(11, 'IFSC Code must be 11 characters').max(11),
  bankName: z.string().optional()
});

type FormValues = z.infer<typeof formSchema>;

const IndForm = () => {
  const router = useRouter();
  const bank: any = sessionStorage.getItem('bank');
  const [value, setValue] = useState<any>(null);
  const { Toast, userInfo } = useGlobalContext();
  const [loading, setLoading] = useState(false);
  const [bankDetails, setBankDetails] = useState<any>(null);

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: '',
      accountNumber: '',
      ifscCode: '',
      bankName: ''
    }
  });

  useEffect(() => {
    let token: any = sessionStorage.getItem('token');
    if (!token) {
      router.replace(`/auth/login`);
    }
  }, []);

  const onSubmit = async (data: FormValues) => {
    try {
      setLoading(true);

      let payload: any = {
        name: data?.name,
        account_number: data?.accountNumber,
        ifsc: data?.ifscCode
      };

      const apiRes = bankDetails
        ? await apis.Bank.update(payload)
        : await apis.Bank.create(payload);

      if (apiRes) {
        Toast.success('Bank details saved successfully!');
        sessionStorage.setItem('bank', 'complete');
        router.replace(`/auth/restaurant/under-review`);
      }
    } catch (error: any) {
      if (error?.response?.data?.message) {
        Toast.error(error.response.data.message);
      } else {
        Toast.error(error?.message || 'An unexpected error occurred.');
      }
      console.error('Error:', error);
    } finally {
      setLoading(false);
    }
  };

  const getBankDetails = async () => {
    try {
      const apiRes = await apis.Bank.get();
      if (apiRes?.data) {
        const { data } = apiRes;
        setBankDetails(data);

        form.setValue('name', data?.name || '');
        form.setValue('accountNumber', data?.account_number || '');
        form.setValue('ifscCode', data?.ifsc || '');
        form.setValue('bankName', data?.bank_name || '');
      }
    } catch (error) {
      console.error('Error fetching bank details:', error);
    }
  };

  useEffect(() => {
    getBankDetails();
  }, []);

  return (
    <div className="no-scrollbar mx-auto mt-3 h-[80vh] max-w-2xl space-y-8 overflow-y-auto">
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-3">
          <div className="grid grid-cols-1 gap-4">
            <FormField
              control={form.control}
              name="name"
              disabled
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Account Holder Name</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Enter account holder name"
                      {...field}
                      maxLength={50}
                      onChange={(e) => {
                        const sanitizedValue = e.target.value.replace(
                          /^\s+/,
                          ''
                        );
                        field.onChange(sanitizedValue);
                      }}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="accountNumber"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Account Number</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Enter your account number"
                      {...field}
                      disabled
                      maxLength={20}
                      onChange={(e) => {
                        const sanitizedValue = e.target.value.replace(/\D/g, '');
                        field.onChange(sanitizedValue);
                      }}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="ifscCode"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>IFSC Code</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Enter IFSC Code (e.g., HDFC0001234)"
                      {...field}
                      disabled
                      maxLength={11}
                      onChange={(e) => {
                        const value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '');
                        field.onChange(value);
                      }}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="bankName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Bank Name</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Bank name (auto-filled from API)"
                      {...field}
                      disabled
                      className="bg-gray-100"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

          {/* <Button
            type="submit"
            disabled={loading}
            className="w-full bg-yellow-400 text-black hover:bg-[var(--primary-brand)]"
          >
            {loading ? 'Submitting...' : 'Next'}
          </Button> */}
        </form>
      </Form>
    </div>
  );
};

export default IndForm;