'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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { useRouter } from 'next/navigation';
import { useGlobalContext } from '@/context/Provider';
import { Country, State, City } from 'country-state-city';
import apis from '@/utils/apis';
import PhoneInput from 'react-phone-input-2';
import 'react-phone-input-2/lib/style.css';

// 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().min(1, 'State is required'),
  city: z.string().min(1, 'City is required'),
  postal_code: z.string().min(1, 'postal code is required'),
  line1: z.string().optional(),
  phone: z.string().optional(),
  date_of_birth: z.string().min(1, 'Enter your date of birth'),
  accountNumber: z
    .string()
    .min(1, 'Account number is required')
    .regex(/^\d+$/, 'Must contain only numbers'),
  routingNumber: z
    .string()
    .min(6, 'Routing number must be 6 digits')
    .regex(/^\d{6}$/, 'Must be exactly 6 digits'),
  idProof: z.any().optional()
});
type FormValues = z.infer<typeof formSchema>;

const BankDetailSidebar = () => {
  const router = useRouter();
  const { Toast } = useGlobalContext();
  const [image, setImage] = useState('');
  const [state, setState] = useState<any>({
    phone: ''
  });
  const [visibleFields, setVisibleFields] = useState(1);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      firstName: '',
      lastName: '',
      country: 'au',
      state: '',
      city: '',
      line1: '',
      postal_code: '',
      accountNumber: '',
      routingNumber: '',
      phone: '',
      date_of_birth: ''
    }
  });
  const countryOptions = Country.getAllCountries().map((country) => ({
    value: country.isoCode,
    label: country.name
  }));



  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) => {
    try {
      let phoneNumber = state?.phone || '';
      let dialCode = state?.value?.dialCode || '';

      if (phoneNumber.startsWith(dialCode)) {
        phoneNumber = phoneNumber.slice(dialCode.length);
      }
      let payload = {
        bank_id: 'string',
        first_name: data?.firstName,
        last_name: data?.lastName,
        country: state?.value?.countryCode,
        date_of_birth: new Date(data?.date_of_birth).toISOString(),
        account_number: data?.accountNumber,
        routing_number: data?.routingNumber,
        file: image,
        address: {
          city: data?.city,
          postal_code: data?.postal_code,
          line1: data?.line1,
          state: data?.state
        },
        country_code: '+' + dialCode,
        phone: phoneNumber
      };
      const apiRes = await apis.Bank.update(payload);
      if (apiRes?.data) {
        router.replace(`/auth/restaurant/under-review`);
      }
    } catch (error: any) {
      console.error('error:', error);
      Toast.error(error.message);
    }
  };

  const getBankDetails = async () => {
    try {
      const apiRes = await apis.Bank.get();
    } catch (error) { }
  };

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

  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);
      //   console.log('uploadd',apiRes)
      setImage(apiRes?.key);
      Toast.success('Image uploaded successfully!');
    } catch (error) {
      Toast.error('Failed to upload image.');
    }
  };
  const handleClear = () => {
    setSelectedFile(null);
    setImage('');
  };
  return (
    <div className="mx-auto mt-3 max-w-2xl space-y-8">
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-3">
          <div className="grid grid-cols-1 gap-4 ">
            <FormField
              control={form.control}
              name="firstName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>First Name</FormLabel>
                  <FormControl>
                    <Input placeholder="Enter your first name" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="lastName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Last Name</FormLabel>
                  <FormControl>
                    <Input placeholder="Enter your last name" {...field} />
                  </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 || ''}
                      className="[&::-webkit-calendar-picker-indicator]:pointer-events-none [&::-webkit-calendar-picker-indicator]:opacity-0"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="phone"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Phone number</FormLabel>
                  <FormControl>
                    <div className="w-full ">
                      <PhoneInput
                        country={'au'}
                        value={state?.phone}
                        masks={{ au: '... ... ....' }}
                        enableSearch
                        placeholder="Phone number"
                        onChange={(phone: any, value: any) => {
                          if (/^\d*$/.test(phone)) {
                            setState({ phone, value });
                            handleInputChange(3, phone, 'phone');
                            const selectedCountry = countryOptions.find(
                              (country) => country.value.toLowerCase() === value?.countryCode.toLowerCase()
                            );
                            form.setValue('country', selectedCountry?.label ?? "N/A")
                          }
                        }}
                      />
                    </div>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="country"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Country</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Enter your country"
                      {...field}
                      disabled
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="state"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>State</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Enter your state"
                      {...field}
                      maxLength={20}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="city"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>City</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Enter your city"
                      {...field}
                      maxLength={20}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="line1"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Street(optional)</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Enter your line1"
                      {...field}
                      maxLength={20}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <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="accountNumber"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Account Number</FormLabel>
                  <FormControl>
                    <Input placeholder="Enter your account number" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

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

            <div className="space-y-4">
              <FormLabel>Upload Id Proof</FormLabel>
              <div className="rounded-lg border-2 border-dashed border-gray-300 p-6">
                {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={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-yellow-400">+ 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"
              // onClick={() => router.push(`/auth/restaurant/under-review`)}
              className="w-full bg-yellow-400 text-black hover:bg-yellow-500"
            >
              Next
            </Button>
          </div>
        </form>
      </Form>
    </div>
  );
};
// export default BankDetailsForm;

export default BankDetailSidebar;
