'use client';

import { Camera } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { useGlobalContext } from '@/context/Provider';
import { useEffect, useRef, useState } from 'react';
import apis, { BUCKET_ROOT } from '@/utils/apis';
import { Icons } from '../icons';
import CountryPickerModal from '../countrycode/page';
import countries from '@/utils/CountryCode.json';
import {
    InputOTP,
    InputOTPGroup,
    InputOTPSlot
} from '@/components/ui/input-otp';
import { Button } from '../ui/button';
import { useRouter } from 'next/navigation';
import { MultiImages } from '../common/MultipleDropzone';
import GoogleAutocomplete from '../Map/GoogleAutoComplete';

interface ProfileFormData {
    avgpreptime: number;
    restaurantName: string;
    contactNumber: string;
    ownerName: string;
    email: string;
    image: string;
    countryCode: string;
    id: string;
}

export function GroceryProfile() {
    const { Toast, userInfo, setUserInfo } = useGlobalContext();
    const [loading, setLoading] = useState(false);
    const [value, setValue] = useState<any>(countries?.[97]);
    const fileInputRef = useRef<HTMLInputElement>(null);
    const [image, setImage] = useState('');
    const [state, setState] = useState<any>('');
    const [restaurantPhotos, setRestaurantPhotos] = useState<string[]>([]);
    const [address, setAddress] = useState<any>(null);

    // Initial values for change detection
    const [initialValues, setInitialValues] = useState<any>(null);

    const [otpModal, setOtpModal] = useState({
        phone: false,
        email: false
    });
    const router = useRouter();

    const [otp, setOtp] = useState({
        phone: '',
        email: ''
    });
    const [verified, setVerified] = useState({
        phone: false,
        email: false
    });

    const [formData, setFormData] = useState<ProfileFormData>({
        restaurantName: userInfo?.restaurant_id?.restaurant_name || '',
        contactNumber:
            (userInfo?.restaurant_id?.country_code || '') +
            (userInfo?.restaurant_id?.restaurant_phone || ''),
        avgpreptime: userInfo?.restaurant_id?.average_preparing_time || 0,
        countryCode: userInfo?.restaurant_id?.country_code || '',
        ownerName: userInfo?.name || '',
        email: userInfo?.email || '',
        image: userInfo?.image || '',
        id: userInfo?.restaurant_id?._id || ''
    });

    useEffect(() => {
        setFormData({
            restaurantName: userInfo?.restaurant_id?.restaurant_name || '',
            contactNumber: userInfo?.restaurant_id?.restaurant_phone || '',
            countryCode: userInfo?.restaurant_id?.country_code || '',
            avgpreptime: userInfo?.restaurant_id?.average_preparing_time || 0,
            ownerName: userInfo?.name || '',
            email: userInfo?.email || '',
            image: userInfo?.image || '',
            id: userInfo?.restaurant_id?._id || ''
        });
        setImage(userInfo?.image || '');
        setState(userInfo?.restaurant_id?.restaurant_phone);
        const matchedCountry = countries.find(
            (country) => country.dial_code === userInfo?.restaurant_id?.country_code
        );
        setValue(matchedCountry || countries?.[97]);
        setVerified({ email: true, phone: true });

        const prefilledPhotos = (userInfo?.restaurant_id?.uploadRestaurantPhotos || []).map((file: any, index: number) => ({
            id: `photo-${index}-${file}`,
            url: file.startsWith('http') ? file : `${BUCKET_ROOT}${file}`,
        }));
        setRestaurantPhotos(prefilledPhotos);

        // Store initial values for change detection
        setInitialValues({
            restaurantName: userInfo?.restaurant_id?.restaurant_name || '',
            contactNumber: userInfo?.restaurant_id?.restaurant_phone || '',
            avgpreptime: userInfo?.restaurant_id?.average_preparing_time || 0,
            ownerName: userInfo?.name || '',
            email: userInfo?.email || '',
            image: userInfo?.image || '',
            restaurantPhotos: prefilledPhotos,
            address: userInfo?.restaurant_id?.address || null,
        });

    }, [userInfo]);

    const prefilledAddress = userInfo?.restaurant_id?.address;

    useEffect(() => {
        if (prefilledAddress) {
            setAddress(prefilledAddress);
        }
    }, [prefilledAddress]);

    const handleAddressSelect = (addressPayload: any) => {
        setAddress(addressPayload);
    };

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        if (name === 'email') {
            setFormData((prev) => ({ ...prev, [name]: value }));
            if (value === userInfo?.email) {
                setVerified({ ...verified, email: true });
            } else {
                setVerified({ ...verified, email: false });
            }
        } else {
            setFormData((prev) => ({ ...prev, [name]: value }));
        }
    };

    const handleUpdate = async () => {
        if (!image) {
            Toast.error('Please upload vendor image');
            return;
        }

        if (!formData.avgpreptime || formData.avgpreptime <= 0) {
            Toast.error('Please enter average preparation time');
            return;
        }

        if (!address || !address.name) {
            Toast.error('Please select an address');
            return;
        }

        let payload: any = {
            restaurant_name: formData?.restaurantName,
            restaurant_phone: state,
            country_code: value?.dial_code,
            owner_name: formData?.ownerName,
            email: formData?.email,
            image: image,
            address: address,
            average_preparing_time: parseInt(formData?.avgpreptime?.toString()) || 0,
            uploadRestaurantPhotos: restaurantPhotos.map((item: any) => item.url)
        };

        try {
            setLoading(true);
            const apiRes = await apis.restaurant.update(formData?.id, payload);
            if (apiRes) {
                const successMsg = 'Profile updated successfully! Your request has been sent to admin for approval.';
                Toast.success(successMsg);
                sessionStorage.setItem('pendingToast', successMsg);
                try {
                    const profileRes = await apis.Profile.getProfile();
                    if (profileRes?.data) {
                        setUserInfo((prev: any) => ({
                            ...prev,
                            ...profileRes.data
                        }));
                    }
                } catch (e) {
                    console.log('Profile refresh error after update:', e);
                }
                setTimeout(() => {
                    sessionStorage.clear();
                    sessionStorage.setItem('pendingToast', successMsg);
                    window.location.href = '/auth/login';
                }, 1500);
            } else {
                Toast.error(apiRes?.message || 'Failed to update profile');
            }
        } catch (error: any) {
            Toast.error(error?.message || error || 'Failed to update profile');
            console.error('Update error:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleFileSelect = () => {
        if (fileInputRef?.current) {
            fileInputRef.current.click();
        }
    };

    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 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;
            }

            handleUploadImage(file);
        }
    };

    const phoneVerify = async (e: any, mobile: any) => {
        e.preventDefault();
        if (verified.phone) {
            Toast.error('Phone number already verified!');
            return;
        }
        if (!mobile || mobile.length < 1) {
            Toast.error('Enter Phone Number!');
            return;
        }
        const minLength = value?.min_length || 6;
        const maxLength = value?.max_length || 15;
        if (mobile.length < minLength) {
            Toast.error(`Vendor contact number must be at least ${minLength} digits!`);
            return;
        }
        if (mobile.length > maxLength) {
            Toast.error(`Vendor contact number must not exceed ${maxLength} digits!`);
            return;
        }

        try {
            let phoneNumber = state || '';
            let dialCode = value?.dial_code || '';

            if (phoneNumber.startsWith(dialCode)) {
                phoneNumber = phoneNumber.slice(dialCode.length);
            }
            let payload = {
                country_code: dialCode,
                phone: phoneNumber
            };
            const apiRes = await apis.Auth.verifyPhoneEmail(payload);
            setOtpModal({ ...otpModal, phone: true });
            sessionStorage.setItem('otpTokenPhone', apiRes?.token);
        } catch (error) {
            Toast.error(error);
        }
    };

    const emailVerify = async (e: any, mail: string) => {
        e.preventDefault();
        if (mail?.length < 1) {
            Toast.error('Enter valid email!');
        }
        if (verified.email) {
            Toast.error('Email already verified!');
            return;
        }
        try {
            let payload = {
                email: mail
            };
            const apiRes = await apis.Auth.verifyPhoneEmail(payload);
            sessionStorage.setItem('otpTokenEmail', apiRes?.token);
            setOtpModal({ ...otpModal, email: true });
        } catch (error) {
            Toast.error(error);
        }
    };

    const emailOtpVerified = async (e: any) => {
        e.preventDefault();
        try {
            let payload = {
                otp: otp.email
            };
            const apiRes = await apis.Auth.VerifyE(payload);
            if (apiRes) {
                sessionStorage.removeItem('otpTokenEmail');
                setOtpModal({ ...otpModal, email: false });
                setVerified({ ...verified, email: true });
            }
        } catch (error) {
            Toast.error(error);
        }
    };

    const phoneOtpVerified = async (e: any) => {
        e.preventDefault();
        try {
            let payload = {
                otp: otp.phone
            };
            const apiRes = await apis.Auth.VerifyP(payload);
            if (apiRes) {
                sessionStorage.removeItem('otpTokenPhone');
                setOtpModal({ ...otpModal, phone: false });
                setVerified({ ...verified, phone: true });
            }
        } catch (error) {
            Toast.error(error);
        }
    };

    const handlePhoneChange = (e: any) => {
        const maxLen = value?.max_length || 15;
        const phoneNumber = e.target.value.replace(/\D/g, '').slice(0, maxLen);
        setState(phoneNumber);
        if (
            phoneNumber === userInfo?.restaurant_id?.restaurant_phone &&
            userInfo?.restaurant_id?.country_code === value?.dial_code
        ) {
            setVerified({ ...verified, phone: true });
        } else {
            setVerified({ ...verified, phone: false });
        }
    };

    const hasChanges = () => {
        if (!initialValues) return false;

        const isArrayEqual = (arr1: any[], arr2: any[]) => {
            if (!arr1 || !arr2) return arr1 === arr2;
            if (arr1.length !== arr2.length) return false;
            return arr1.every((item, index) => {
                if (typeof item === 'object' && item !== null) {
                    return JSON.stringify(item) === JSON.stringify(arr2[index]);
                }
                return item === arr2[index];
            });
        };

        return (
            formData.restaurantName !== initialValues.restaurantName ||
            state !== initialValues.contactNumber ||
            formData.avgpreptime?.toString() !== initialValues.avgpreptime?.toString() ||
            formData.ownerName !== initialValues.ownerName ||
            formData.email !== initialValues.email ||
            image !== initialValues.image ||
            JSON.stringify(address) !== JSON.stringify(initialValues.address) ||
            !isArrayEqual(restaurantPhotos, initialValues.restaurantPhotos)
        );
    };

    const isSaveDisabled = !(verified.phone && verified.email) || !hasChanges();

    return (
        <>
            <div className="p-4 pb-0">
                <div className="relative mx-auto mb-8 h-[150px] w-[150px]">
                    {image ? (
                        <img
                            src={BUCKET_ROOT + image}
                            alt="Vendor"
                            className="h-[140px] w-[140px] rounded-full border-[1px] border-[var(--primary-brand)] object-cover"
                        />
                    ) : (
                        <div className="flex h-[140px] w-[140px] items-center justify-center rounded-full border-[1px] border-[var(--primary-brand)]">
                            <Icons.MenuIcon />
                        </div>
                    )}
                    <button
                        className="absolute bottom-3 right-3 rounded-full bg-[var(--primary-brand)] p-2 text-white hover:bg-[var(--primary-brand)]"
                        onClick={(e) => {
                            e.preventDefault();
                            handleFileSelect();
                        }}
                    >
                        <Camera className="h-4 w-4" />
                    </button>
                    <Input
                        type="file"
                        accept=".jpg,.jpeg,.png"
                        hidden
                        ref={fileInputRef}
                        onChange={handleFileChange}
                        className="hidden"
                    />
                    {!image && (
                        <p className="mt-2 text-xs text-red-500 text-center">Vendor image is required</p>
                    )}
                </div>

                <form className="w-full space-y-6">
                    <div>
                        <label className="text-sm font-medium text-[#0C1018]">
                            Vendor Name
                        </label>
                        <Input
                            name="restaurantName"
                            className="mt-1 h-[45px]"
                            placeholder="Enter Vendor name"
                            value={formData.restaurantName}
                            onChange={handleChange}
                            maxLength={15}
                        />
                    </div>

                    <div>
                        <label className="text-sm font-medium text-[#0C1018]">
                            Vendor Contact Number
                        </label>
                        <div className="flex flex-row rounded-lg border border-solid transition-colors focus-within:border-[var(--primary-brand)]">
                            <CountryPickerModal setValue={setValue} value={value} />
                            <Input
                                name="contactNumber"
                                className=" h-[45px] border-none shadow-none"
                                placeholder="Enter contact number"
                                value={state}
                                onChange={(e: any) => handlePhoneChange(e)}
                                minLength={value?.min_length || 6}
                                maxLength={value?.max_length || 15}
                            />
                            <button
                                type="button"
                                className="flex h-[48px] items-center justify-center p-2 text-[14px] font-[600] text-[var(--primary-brand)]"
                                onClick={(e: any) => phoneVerify(e, state)}
                            >
                                {verified.phone ? 'Verified' : 'Verify'}
                            </button>
                        </div>
                    </div>
                    {otpModal.phone && (
                        <div className="flex flex-row gap-4 space-y-1">
                            <InputOTP
                                className="w-full"
                                maxLength={4}
                                value={otp.phone}
                                onChange={(value: string) => setOtp({ ...otp, phone: value })}
                            >
                                {[...Array(4)].map((_, index) => (
                                    <InputOTPGroup key={index}>
                                        <InputOTPSlot
                                            index={index}
                                            className="h-11 w-14 rounded-md border border-gray-300 bg-white text-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        />
                                    </InputOTPGroup>
                                ))}
                            </InputOTP>
                            <Button
                                onClick={(e: any) => phoneOtpVerified(e)}
                                className="theme-background h-11 w-full text-white"
                            >
                                Verify
                            </Button>
                        </div>
                    )}

                    <div>
                        <label className="text-sm font-medium text-[#0C1018]">
                            Average Preparation time (in minutes) <span className="text-red-500">*</span>
                        </label>
                        <Input
                            name="avgpreptime"
                            className="mt-1 h-[45px]"
                            placeholder="Enter average preparation time"
                            value={formData.avgpreptime}
                            onChange={handleChange}
                            maxLength={15}
                        />
                        {(!formData.avgpreptime || formData.avgpreptime <= 0) && (
                            <p className="mt-1 text-xs text-red-500">Average preparation time is required</p>
                        )}
                    </div>

                    <div>
                        <label className="text-sm font-medium text-[#0C1018]">
                            Owner Name
                        </label>
                        <Input
                            name="ownerName"
                            className="mt-1 h-[45px]"
                            placeholder="Enter owner name"
                            value={formData.ownerName}
                            onChange={handleChange}
                        />
                    </div>

                    <div>
                        <label className="text-sm font-medium text-[#0C1018]">
                            Email address
                        </label>
                        <div className="flex flex-row rounded-lg border border-solid transition-colors focus-within:border-[var(--primary-brand)]">
                            <Input
                                type="email"
                                name="email"
                                className="mt-1 h-[45px] border-none shadow-none"
                                placeholder="Enter email address"
                                value={formData.email}
                                onChange={handleChange}
                            />
                            <button
                                type="button"
                                className="flex h-[48px] items-center justify-center p-2 text-[14px] font-[600] text-[var(--primary-brand)]"
                                onClick={(e: any) => emailVerify(e, formData.email)}
                            >
                                {verified.email ? 'Verified' : 'Verify'}
                            </button>
                        </div>
                    </div>
                    {otpModal.email && (
                        <div className="flex flex-row gap-4 space-y-1">
                            <InputOTP
                                className="w-full"
                                maxLength={4}
                                value={otp.email}
                                onChange={(value: string) => setOtp({ ...otp, email: value })}
                            >
                                {[...Array(4)].map((_, index) => (
                                    <InputOTPGroup key={index}>
                                        <InputOTPSlot
                                            index={index}
                                            className="h-11 w-14 rounded-md border border-gray-300 bg-white text-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        />
                                    </InputOTPGroup>
                                ))}
                            </InputOTP>
                            <Button
                                onClick={(e: any) => emailOtpVerified(e)}
                                className="theme-background h-11 w-full text-white"
                            >
                                Verify
                            </Button>
                        </div>
                    )}

                    <div>
                        <label className="text-sm font-medium text-[#0C1018]">
                            Upload Vendor Photos <span className="text-red-500">*</span>
                        </label>
                        <MultiImages
                            images={restaurantPhotos}
                            addImages={setRestaurantPhotos}
                        />
                        {restaurantPhotos.length === 0 && (
                            <p className="mt-1 text-xs text-red-500">At least one vendor photo is required</p>
                        )}
                    </div>

                    <div className="w-full">
                        <label
                            htmlFor="address-autocomplete"
                            className="text-sm font-medium text-[#0C1018]"
                        >
                            Address <span className="text-red-500">*</span>
                        </label>
                        <div id="address-autocomplete">
                            <GoogleAutocomplete
                                initialValue={userInfo?.restaurant_id?.address?.name || ''}
                                onAddressSelect={handleAddressSelect}
                            />
                        </div>
                        {!address?.name && (
                            <p className="mt-1 text-xs text-red-500">Address is required</p>
                        )}
                    </div>
                </form>
            </div>

            <div className="mt-6 p-6 pt-0">
                <p className="mb-2 text-sm text-gray-500">
                    Note: After updating your profile, your request will be sent to admin for approval and you will be redirected to the login page.
                </p>
                <button
                    onClick={handleUpdate}
                    disabled={isSaveDisabled}
                    className={`w-full rounded-lg py-3 font-medium text-white transition-colors ${isSaveDisabled
                        ? 'bg-gray-400 cursor-not-allowed'
                        : 'bg-[var(--primary-brand)] hover:bg-[var(--primary-brand)]'
                        }`}
                >
                    Save Changes
                </button>
            </div>
        </>
    );
}
