'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 { useRouter } from 'next/navigation';
import { useGlobalContext } from '@/context/Provider';
import { Country } from 'country-state-city';
import apis, { BUCKET_ROOT } from '@/utils/apis';
import dayjs from 'dayjs';
import CountryPickerModal from '../countrycode/page';
import countries from '@/utils/CountryCode.json';
import IndForm from './indForm/indForm';

// 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().optional(),
  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'),
  routingNumber: z.string().optional(),
  idProof: z.any().optional()
});

type FormValues = z.infer<typeof formSchema>;

const BankDetailSidebar = () => {
  const router = useRouter();
  const { Toast, userInfo } = useGlobalContext();
  const [image, setImage] = useState('');
  const [value, setValue] = useState<any>(countries?.[13]);
  const [state, setState] = useState<any>('');
  const [bank_id, setBank_id] = useState('');
  const [loading, setLoading] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [bankDetails, setBankDetails] = useState<any>(null);
  const [isIndia, setIsIndia] = useState(false);

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

  const countryOptions = Country.getAllCountries().map((country) => ({
    value: country.isoCode,
    label: country.name
  }));

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

      let phoneNumber = state || data.phone || '';
      let dialCode = value?.dial_code || '';

      if (phoneNumber.startsWith(dialCode)) {
        phoneNumber = phoneNumber.slice(dialCode.length);
      }

      let payload = {
        bank_id: bank_id,
        first_name: data?.firstName,
        last_name: data?.lastName,
        country: value?.code,
        date_of_birth: data?.date_of_birth ? new Date(data.date_of_birth).toISOString() : null,
        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) {
        Toast.success('Bank details updated successfully!');
        router.replace(`/auth/restaurant/under-review`);
      }
    } catch (error: any) {
      console.error('Error:', error);
      Toast.error(error.message || 'Failed to update bank details');
    } finally {
      setLoading(false);
    }
  };

  const getBankDetails = async () => {
    try {
      const apiRes = await apis.Bank.get();
      const data = apiRes?.data || {};
      setBankDetails(data);
      const countryIsIndia = !!(data?.ifsc || data?.bank_name);
      setIsIndia(countryIsIndia);

      if (!countryIsIndia) {
        const firstName = data?.first_name || userInfo?.name?.split(' ')[0] || '';
        const lastName = data?.last_name || userInfo?.name?.split(' ').slice(1).join(' ') || userInfo?.name?.split(' ')[0] || '';
        const dateOfBirth = data?.date_of_birth 
          ? dayjs(data.date_of_birth).format('YYYY-MM-DD') 
          : '';
        const accountNumber = data?.account_number || userInfo?.cashfree_beneficiary_account_id || '';
        const routingNumber = data?.routing_number || '';
        const city = data?.address?.city || '';
        const stateVal = data?.address?.state || '';
        const postalCode = data?.address?.postal_code || '';
        const line1 = data?.address?.line1 || '';

        form.setValue('firstName', firstName);
        form.setValue('lastName', lastName);
        if (dateOfBirth) {
          form.setValue('date_of_birth', dateOfBirth);
        }
        form.setValue('accountNumber', accountNumber);
        form.setValue('routingNumber', routingNumber);
        form.setValue('city', city);
        form.setValue('state', stateVal);
        form.setValue('postal_code', postalCode);
        form.setValue('line1', line1);

        const countryStr = data?.country || 'India';
        const selectedCountry = countryOptions.find(
          (c) => c.value.toLowerCase() === countryStr.toLowerCase()
        );
        form.setValue('country', selectedCountry?.label ?? countryStr);

        const phoneVal = data?.phone || userInfo?.phone || '';
        setState(phoneVal);
        setImage(data?.file_path || '');
        setBank_id(data?._id || '');

        const rawDialCode = data?.country_code || userInfo?.country_code || '91';
        const dialCodeToMatch = rawDialCode.startsWith('+') ? rawDialCode : `+${rawDialCode}`;
        const matchedCountry = countries.find(
          (c) => c?.dial_code === dialCodeToMatch
        );
        if (matchedCountry) {
          setValue(matchedCountry);
        }
      }
    } catch (error) {
      console.error('Error fetching bank details:', error);
    }
  };

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

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

    if (file) {
      const maxFileSize = 5 * 1024 * 1024;
      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 {
      setLoading(true);
      const apiRes = await apis.Common.uploadFile('file', file);
      setImage(apiRes?.key);
      Toast.success('Image uploaded successfully!');
    } catch (error) {
      Toast.error('Failed to upload image.');
    } finally {
      setLoading(false);
    }
  };

  const handleClear = () => {
    setSelectedFile(null);
    setImage('');
  };

  return (
    <div className="mx-auto mt-3 max-w-2xl space-y-8">
      {userInfo?.cashfree_beneficiary_account_id ? (
        <div className="mx-auto mt-4 max-w-md p-6 bg-gradient-to-br from-indigo-900 via-slate-900 to-indigo-950 text-white rounded-2xl shadow-xl border border-indigo-500/20 relative overflow-hidden">
          {/* Decorative background light */}
          <div className="absolute -top-10 -right-10 w-40 h-40 bg-indigo-500/10 rounded-full blur-3xl"></div>
          <div className="absolute -bottom-10 -left-10 w-40 h-40 bg-purple-500/10 rounded-full blur-3xl"></div>
          
          <div className="flex justify-between items-start mb-8">
            <div>
              <h3 className="text-lg font-bold tracking-wide text-indigo-200">CASHFREE PAYOUT</h3>
              <p className="text-xs text-slate-400 mt-0.5">Active Beneficiary Account</p>
            </div>
            <div className="h-8 w-12 bg-white/10 rounded-md flex items-center justify-center border border-white/10 font-bold text-xs tracking-widest text-slate-300">
              CF
            </div>
          </div>

          <div className="space-y-6">
            <div>
              <span className="text-[10px] text-slate-400 uppercase tracking-widest block mb-1">Beneficiary ID</span>
              <span className="text-lg font-mono font-semibold tracking-wider text-slate-100 bg-white/5 px-2.5 py-1.5 rounded-lg border border-white/5">
                {userInfo.cashfree_beneficiary_account_id}
              </span>
            </div>

            <div className="grid grid-cols-2 gap-4 pt-2 border-t border-white/5">
              <div>
                <span className="text-[10px] text-slate-400 uppercase tracking-widest block mb-1">Holder Name</span>
                <span className="text-sm font-semibold text-slate-200">{userInfo.name || 'N/A'}</span>
              </div>
              <div>
                <span className="text-[10px] text-slate-400 uppercase tracking-widest block mb-1">Phone</span>
                <span className="text-sm font-semibold text-slate-200">
                  {userInfo.country_code ? `+${userInfo.country_code} ` : ''}
                  {userInfo.phone || 'N/A'}
                </span>
              </div>
            </div>

            <div className="pt-2">
              <span className="text-[10px] text-slate-400 uppercase tracking-widest block mb-1">Email Address</span>
              <span className="text-sm font-semibold text-slate-200">{userInfo.email || 'N/A'}</span>
            </div>
          </div>
        </div>
      ) : isIndia ? (
        <IndForm />
      ) : (
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-3">
            <div className="grid grid-cols-1 gap-4">
              <FormField
                control={form.control}
                disabled
                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"
                disabled
                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"
                disabled
                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"
                disabled
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Phone number</FormLabel>
                    <FormControl>
                      <div className="flex w-full flex-row">
                        <CountryPickerModal setValue={setValue} value={value} />
                        <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);
                          }}
                        />
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

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

              <FormField
                control={form.control}
                disabled
                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"
                disabled
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>City</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Enter your city"
                        {...field}
                        maxLength={20}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                disabled
                name="line1"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Street (optional)</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Enter your street address"
                        {...field}
                        maxLength={50}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

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

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

              <div className="space-y-4">
                <FormLabel>ID Proof</FormLabel>
                <div className="rounded-lg border-2 border-dashed border-gray-300 bg-gray-100 p-6">
                  {image ? (
                    <div className="flex items-center justify-center">
                      <img
                        src={BUCKET_ROOT + image}
                        alt="ID Proof Preview"
                        className="h-16 w-16 rounded-lg object-cover"
                      />
                    </div>
                  ) : (
                    <div className="flex flex-col items-center">
                      <p className="text-sm text-gray-500">No ID proof uploaded</p>
                    </div>
                  )}
                </div>
              </div>

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

export default BankDetailSidebar;