'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 { Upload } from 'lucide-react';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import AuthLayout from '@/components/layout/layout';
import authBanner from '@/assets/images/AuthImages/restaurant.png';
import { useRouter } from 'next/navigation';
import { useGlobalContext } from '@/context/Provider';
import PhoneInput from 'react-phone-input-2';
import apis from '@/utils/apis';
import 'react-phone-input-2/lib/style.css';
import { Country } from 'country-state-city';
import dayjs from 'dayjs';
import CountryPickerModal from '@/components/countrycode/page';
import countries from '@/utils/CountryCode.json';

// Form validation schema
const formSchema = z.object({
  firstName: z.string().min(1, 'First name is required'),
  lastName: z.string().min(1, 'Last name is required'),
  country: z.string().min(1, 'Country is required'),
  state: z.string().optional(),
  city: z.string().optional(),

  postal_code: z.string().optional(),
  line1: z.string().optional(),
  phone: z.string().optional(),
  date_of_birth: z.string().optional(),
  accountNumber: z
    .string()
    .min(1, 'Account number is required')
    .regex(/^\d+$/, 'Must contain only numbers'),
  routingNumber: z.string().optional(),
  idProof: z.any().optional(),
  ifscCode: z.string().optional(),
  email: z.string().optional(),
  ssnlastnumber: z.string().optional()
});

type FormValues = z.infer<typeof formSchema>;

const BankDetailsForm = () => {
  const router = useRouter();
  const food: any = sessionStorage.getItem('food');
  const bank: any = sessionStorage.getItem('bank');
  const [value, setValue] = useState<any>(null);
  const { Toast, userInfo } = useGlobalContext();
  const [image, setImage] = useState('');
  const [state, setState] = useState<any>('');
  const [loading, setLoading] = useState(false);
  const [visibleFields, setVisibleFields] = useState(1);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [errMsg, setErrMsg] = useState('');

  useEffect(() => {
    let token: any = sessionStorage.getItem('token');
    if (!token) {
      router.replace(`/auth/login`);
    }
  }, []);
  const countryOptions = Country.getAllCountries().map((country) => ({
    value: country.isoCode,
    label: country.name
  }));
  const [country, setCountry] = useState('India');

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      firstName: '',
      lastName: '',
      country: 'india',
      state: '',
      city: '',
      line1: '',
      postal_code: '',
      accountNumber: '',
      routingNumber: '',
      phone: '',
      date_of_birth: dayjs().subtract(18, 'years').format('YYYY-MM-DD'),
      ifscCode: '',
      email: '',
      ssnlastnumber: ''
    }
  });

  const handleInputChange = (index: any, event: any, type?: any) => {
    const value = type ? event : event.target?.value.trim();
    if (value !== '' && visibleFields === index) {
      setVisibleFields((prev) => prev + 1);
    }
  };
  const onSubmit = async (data: FormValues) => {
    if (!image && country.toLowerCase() == 'other') {
      Toast.error('Upload Id proof!');
      return;
    }
    try {
      setLoading(true);
      let phoneNumber = state || '';
      let dialCode = value?.dial_code || '';
      let countryCod = value?.code?.toLowerCase() || '';

      if (phoneNumber.startsWith(dialCode)) {
        phoneNumber = phoneNumber.slice(dialCode.length);
      }
      let payload: any = {
        first_name: data?.firstName,
        last_name: data?.lastName,
        date_of_birth: data?.date_of_birth
          ? new Date(data.date_of_birth).toISOString()
          : null,
        account_number: data?.accountNumber,
        country_code: dialCode,
        phone: phoneNumber
      };
      if (country?.toLowerCase() === 'india') {
        payload['ifsc'] = data?.ifscCode;
        payload['country'] = 'IN';
        payload['email'] = data?.email;
        payload[`address`] = {
          line1: data?.line1
        };
      } else {
        payload['file'] = image;
        payload['routing_number'] = data?.routingNumber;
        payload['country'] = countryCod;
        payload[`address`] = {
          city: data?.city,
          postal_code: data?.postal_code,
          line1: data?.line1,
          state: data?.state
        };
        payload['ssn_last4_number'] = data?.ssnlastnumber;
      }
      const apiRes = await apis.Bank.create(payload);
      if (apiRes) {
        sessionStorage.setItem('bank', 'complete');
        router.replace(`/auth/complete-profile`);
      }
    } catch (error: any) {
      console.error('Form submission error:', error);
      Toast.error(error);
    } finally {
      setLoading(false);
    }
  };

  const getBankDetails = async () => {
    try {
      const apiRes = await apis.Bank.get();
      if (apiRes?.data) {
        const { data } = apiRes;
        form.setValue('firstName', data?.first_name);
        form.setValue('lastName', data?.last_name);
        form.setValue(
          'date_of_birth',
          dayjs(data?.date_of_birth).format('YYYY-MM-DD')
        );
        form.setValue('accountNumber', data?.account_number);
        form.setValue('routingNumber', data?.routing_number);
        form.setValue('city', data?.address?.city);
        const selectedCountry = countryOptions.find(
          (country) =>
            country.value.toLowerCase() === data?.country.toLowerCase()
        );
        if (country.toLowerCase() == 'other') {
          const matchedCountry = countries.find(
            (country) => country.dial_code === '61'
          );
          setValue(matchedCountry);
        } else {
          const matchedCountry = countries.find(
            (country) => country.dial_code === '91'
          );
          setValue(matchedCountry);
        }

        form.setValue('country', selectedCountry?.label ?? 'N/A');
        form.setValue('state', data?.address?.state);
        form.setValue('postal_code', data?.address?.postal_code);
        setState(data?.phone);
        setImage(data?.file_path);
      }
    } catch (error) { }
  };

  useEffect(() => {
    if (value && country.toLowerCase() == 'other') {
      form.setValue('country', value?.name ?? 'N/A');
    }
  }, [value]);

  useEffect(() => {
    if (bank === 'complete') {
      getBankDetails();
    } else {
      let name = (userInfo?.name ?? '').split(' ');
      form.setValue('firstName', name?.[0]);
      form.setValue('lastName', name?.[name.length - 1]);
      if (country.toLowerCase() === 'india') {
        form.setValue('accountNumber', '50100123456789');
        form.setValue('ifscCode', 'HDFC0001234');
        form.setValue('routingNumber', '110000');
        const matchedCountry = countries.find(
          (country) => country.dial_code === '91'
        );
        setValue(matchedCountry);
        setState('29999 9999');
      } else {
        form.setValue('accountNumber', '000123456');
        form.setValue('routingNumber', '110000');
        form.setValue('city', 'Sydney');
        form.setValue('state', 'NSW');
        form.setValue('postal_code', '2000');
        form.setValue('line1', '100 George St');
        form.setValue('ssnlastnumber', '0000');
        const matchedCountry = countries.find(
          (country) => country.dial_code === '61'
        );
        setValue(matchedCountry);
        setState('435345345');
      }
    }
  }, [country, userInfo]);

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    event.preventDefault();
    const file = event.target.files?.[0];

    if (file) {
      const maxFileSize = 5 * 1024 * 1024; // 5MB Limit
      const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg'];

      if (!allowedTypes.includes(file.type)) {
        Toast.error('Only JPG and PNG images are allowed.');
        return;
      }

      if (file.size > maxFileSize) {
        Toast.error('Image size cannot be more than 5MB.');
        return;
      }

      setSelectedFile(file);
      handleUploadImage(file);
    }
  };
  const handleUploadImage = async (file: File) => {
    try {
      const apiRes = await apis.Common.uploadFile('file', file);
      setImage(apiRes?.image_url);
      Toast.success('Image uploaded successfully!');
    } catch (error) {
      Toast.error('Failed to upload image.');
    }
  };
  const handleClear = () => {
    setSelectedFile(null);
    setImage('');
  };

  const validatePhoneNumber = (phoneNumber: string) => {
    if (!phoneNumber) {
      setErrMsg('Phone number is required!');
      return false;
    }

    const minLength = value?.min_length || 6;
    const maxLength = value?.max_length || 15;
    const phoneLength = phoneNumber.length;

    if (phoneLength < minLength) {
      setErrMsg(
        `Phone number must be at least ${minLength} digits for ${value?.name}!`
      );
      return false;
    }

    if (phoneLength > maxLength) {
      setErrMsg(
        `Phone number must not exceed ${maxLength} digits for ${value?.name}!`
      );
      return false;
    }

    setErrMsg('');
    return true;
  };

  useEffect(() => {
    if (state) {
      validatePhoneNumber(state);
    }
  }, [value]);

  return (
    <div className="w-full">
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit, (errors) => {
          })}
          className="space-y-4"
        >
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <FormField
              control={form.control}
              name="country"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Country</FormLabel>
                  <FormControl>
                    <select
                      {...field}
                      value={country}
                      onChange={(e) => {
                        field.onChange(e);
                        setCountry(e.target.value);
                      }}
                      className="w-full rounded-md border border-gray-300 bg-white p-2.5 text-sm text-gray-700"
                    >
                      <option value="">Select Country</option>
                      <option value="India">India</option>
                      <option value="Other">Other</option>
                    </select>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="firstName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>First Name</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Enter your first name"
                      {...field}
                      onChange={(e) => {
                        const sanitizedValue = e.target.value
                          .replace(/^\s+/, '') // remove leading spaces
                          .replace(/[^A-Za-z\s]/g, '') // remove numbers & special characters
                          .replace(/\s{2,}/g, ' '); // collapse multiple spaces into one

                        field.onChange(sanitizedValue);
                      }}
                      maxLength={20}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="lastName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Last Name</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Enter your last name"
                      {...field}
                      onChange={(e) => {
                        const sanitizedValue = e.target.value
                          .replace(/^\s+/, '') // remove leading spaces
                          .replace(/[^A-Za-z\s]/g, '') // remove numbers & special characters
                          .replace(/\s{2,}/g, ' '); // collapse multiple spaces into one

                        field.onChange(sanitizedValue);
                      }}
                      maxLength={20}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="date_of_birth"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Date of Birth</FormLabel>
                  <FormControl>
                    <Input
                      type="date"
                      placeholder="Select your date of birth"
                      {...field}
                      value={field.value || ''}
                      min={dayjs().subtract(100, 'years').format('YYYY-MM-DD')}
                      max={dayjs().format('YYYY-MM-DD')}
                      className="[&::-webkit-calendar-picker-indicator]:pointer-events-none [&::-webkit-calendar-picker-indicator]:opacity-0"
                      onFocus={(e) => e.target.showPicker()}
                      onChange={(e) => {
                        const selectedDate = new Date(e.target.value);
                        const today = new Date();

                        // Calculate age
                        let age = today.getFullYear() - selectedDate.getFullYear();
                        const monthDiff = today.getMonth() - selectedDate.getMonth();
                        if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < selectedDate.getDate())) {
                          age--;
                        }

                        if (selectedDate > today) {
                          form.setError('date_of_birth', {
                            type: 'manual',
                            message: 'Date of birth cannot be in the future.'
                          });
                        } else if (age < 16) {
                          form.setError('date_of_birth', {
                            type: 'manual',
                            message: 'You must be at least 16 years old.'
                          });
                        } else {
                          form.clearErrors('date_of_birth');
                        }
                        field.onChange(e);
                      }}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {country.toLowerCase() === 'india' && (
              <FormField
                control={form.control}
                name="email"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Email</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Enter your email"
                        {...field}
                        maxLength={50}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            )}

            <FormField
              control={form.control}
              name="phone"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Phone number</FormLabel>
                  <FormControl>
                    <div className="flex w-full flex-row">
                      <CountryPickerModal
                        setValue={setValue}
                        value={value}
                        isOpenAllowed={
                          country.toLocaleLowerCase() === 'india' ? false : true
                        }
                      />
                      <Input
                        placeholder="Enter your phone number"
                        className="h-[48px] bg-[#f9fafb]"
                        value={state}
                        onChange={(e: any) => {
                          const phoneNumber = e.target.value.replace(/\D/g, '');
                          setState(phoneNumber);
                          if (errMsg) {
                            setErrMsg('');
                          }
                        }}
                        onBlur={() => {
                          if (state) {
                            validatePhoneNumber(state);
                          }
                        }}
                        minLength={value?.min_length || 6}
                        maxLength={value?.max_length || 15}
                      />
                    </div>
                  </FormControl>
                  {errMsg && (
                    <p className="text-[12px] font-medium text-red-600 mt-1">
                      {errMsg}
                    </p>
                  )}
                  <FormMessage />
                </FormItem>
              )}
            />

            {country.toLowerCase() === 'other' && (
              <FormField
                control={form.control}
                name="state"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>State</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Enter your state"
                        {...field}
                        maxLength={20}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            )}

            {country.toLowerCase() === 'other' && (
              <FormField
                control={form.control}
                name="city"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>City</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Enter your city"
                        {...field}
                        maxLength={20}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            )}

            {country.toLowerCase() === 'other' && (
              <FormField
                control={form.control}
                name="postal_code"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Postal code</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Enter your postal code"
                        {...field}
                        maxLength={6}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            )}

            <FormField
              control={form.control}
              name="line1"
              render={({ field }) => (
                <FormItem className="col-span-1 md:col-span-2">
                  <FormLabel>Street (optional)</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Enter street address"
                      {...field}
                      maxLength={50}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="accountNumber"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Account Number</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Enter your account number"
                      {...field}
                      maxLength={20}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {country.toLowerCase() === 'other' && (
              <FormField
                control={form.control}
                name="routingNumber"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Routing Number</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Enter your routing number"
                        {...field}
                        maxLength={20}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            )}

            {country.toLowerCase() === 'other' && (
              <FormField
                control={form.control}
                name="ssnlastnumber"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>SSN (Last 4 Digits)</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Enter last 4 digits of SSN"
                        {...field}
                        maxLength={4}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            )}

            {country.toLowerCase() === 'india' && (
              <FormField
                control={form.control}
                name="ifscCode"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>IFSC Code</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Enter your IFSC Code"
                        {...field}
                        maxLength={20}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            )}
          </div>
          {country.toLowerCase() == 'other' && (
            <div className="space-y-4">
              <FormLabel>Upload Id Proof</FormLabel>
              <div className="rounded-lg border-2 border-dashed border-gray-300 p-6">
                {image || selectedFile ? (
                  // <div className="flex items-center justify-center">
                  //   <img
                  //     src={URL.createObjectURL(selectedFile)}
                  //     alt="Preview"
                  //     className="w-16 h-16 rounded-lg object-cover"
                  //   />
                  //   <div>
                  //     {/* <div className="font-semibold text-xs theme-color">{fileName}</div> */}
                  //   </div>
                  // </div>
                  <div className="flex items-center justify-between space-x-4">
                    <div className="flex items-center gap-2">
                      <img
                        src={
                          image ||
                          (selectedFile
                            ? URL.createObjectURL(selectedFile)
                            : '')
                        }
                        alt="Preview"
                        className="h-16 w-16 rounded-lg object-cover"
                      />
                      <div>
                        {/* <div className="font-semibold text-xs theme-color">{fileName}</div> */}
                      </div>
                    </div>
                    {/* {!loading && ( */}
                    <button
                      type="button"
                      className="text-gray cursor-pointer text-[12px] underline hover:text-red-500 focus:outline-none"
                      onClick={handleClear}
                    >
                      Clear
                    </button>
                    {/* )} */}
                  </div>
                ) : (
                  <div className="flex flex-col items-center">
                    <Upload className="mb-2 h-8 w-8 text-gray-400" />
                    <label className="cursor-pointer">
                      <span className="text-[var(--primary-brand)] font-medium">+ Upload photo</span>
                      <input
                        type="file"
                        className="hidden"
                        accept=".jpg,.jpeg,.png"
                        onChange={handleFileChange}
                      />
                    </label>
                    <p className="mt-1 text-sm text-gray-500">
                      Supported formats: .jpg, .jpeg
                    </p>
                  </div>
                )}
              </div>
            </div>
          )}

          <Button
            type="submit"
            className="h-11 w-full"
            variant={'theme'}
            loading={loading}
            disabled={loading}
          // onClick={() => router.push(`/auth/restaurant/under-review`)}
          // className="w-full bg-yellow-400 text-black hover:bg-[var(--primary-brand)]"
          >
            Next
          </Button>
        </form>
      </Form>
    </div>
  );
};

export default function BankDetails() {
  return (
    <AuthLayout
      title="Bank account Details"
      des="This is where ReadyEats will deposit your money."
      image={authBanner.src}
    >
      <BankDetailsForm />
    </AuthLayout>
  );
}
