import { useEffect, useState } from 'react';
import Select from 'react-select';
import { Country, State, City } from 'country-state-city';
import { Controller, useForm } from 'react-hook-form';
import WebsiteLayout from '@/components/Layouts/WebsiteLayout';
import {
  useEditUserProfileMutation,
  useGetUserProfileByIdQuery,
} from '@/lib/redux/services/Userflow/UserDashboard.api';
import { useSession } from 'next-auth/react';
import toast from 'react-hot-toast';
import { useRouter } from 'next/router';
import { Col, Row, Container, Spinner } from 'react-bootstrap';
import ProfilePictureUpload from '@/components/Form/ProfilePictureUpload';

const customStyles = {
  control: (provided: any) => ({
    ...provided,
    borderRadius: '50px',
    background: '#FFF',
    padding: '10px 16px 10px 50px',
    border: '1px solid #1C1C1C',
    boxShadow: '6px 8px 24px 0px rgba(115, 115, 115, 0.16)',
  }),
  indicatorSeparator: () => ({ display: 'none' }),
};

export default function EditProfile() {
  const [image, setImage] = useState<File | string | null>(null);
  const [countries, setCountries] = useState<any[]>([]);
  const [states, setStates] = useState<any[]>([]);
  const [cities, setCities] = useState<any[]>([]);

  const { data: session }: any = useSession();
  const token = session?.user?.token;
  const skip = !token;
  const router = useRouter();

  const { data: UserProfile, refetch } = useGetUserProfileByIdQuery({ token }, { skip });
  const [EditUserProfile, {isLoading}] = useEditUserProfileMutation();

  const { register, handleSubmit, setValue, control, watch } = useForm<any>({
    defaultValues: {
      name: '',
      phonenumber: '',
      country: null,
      state: null,
      city: null,
    },
  });

  const selectedCountry = watch('country');
  const selectedState = watch('state');

  // Load countries once
  useEffect(() => {
    const allCountries = Country.getAllCountries().map((c) => ({
      value: c.isoCode,
      label: c.name,
    }));
    setCountries(allCountries);
  }, []);

  // Load states when country changes
  useEffect(() => {
    if (selectedCountry) {
      const allStates = State.getStatesOfCountry(selectedCountry.value).map((s) => ({
        value: s.isoCode,
        label: s.name,
      }));
      setStates(allStates);
      setValue('state', null); // Reset state when country changes
      setCities([]);
      setValue('city', null); // Reset city when country changes
    }
  }, [selectedCountry, setValue]);

  // Load cities when state changes
  useEffect(() => {
    if (selectedCountry && selectedState) {
      const allCities = City.getCitiesOfState(selectedCountry.value, selectedState.value).map(
        (ci) => ({
          value: ci.name,
          label: ci.name,
        })
      );
      setCities(allCities);
      setValue('city', null); // Reset city when state changes
    }
  }, [selectedState, selectedCountry, setValue]);

  // Pre-fill form with user data
  useEffect(() => {
    if (UserProfile?.data) {
      const { userDetails } = UserProfile.data;

      setValue('name', userDetails?.name || '');
      setValue('phonenumber', userDetails?.phonenumber || '');

      if (userDetails?.image?.mediaUrl) {
        setImage(userDetails.image.mediaUrl);
      }

      // Restore country, state, city values
      if (userDetails?.address) {
        const countryObj = {
          value: userDetails.address,
          label: Country.getCountryByCode(userDetails.address)?.name || userDetails.address,
        };
        setValue('country', countryObj);

        // Set states based on country
        const allStates = State.getStatesOfCountry(userDetails.address).map((s) => ({
          value: s.isoCode,
          label: s.name,
        }));
        setStates(allStates);

        if (userDetails?.stateCode) {
          const stateObj = {
            value: userDetails.stateCode,
            label:
              State.getStateByCodeAndCountry(userDetails.stateCode, userDetails.countryCode)
                ?.name || userDetails.stateCode,
          };
          setValue('state', stateObj);

          // Set cities based on state
          const allCities = City.getCitiesOfState(
            userDetails.countryCode,
            userDetails.stateCode
          ).map((ci) => ({
            value: ci.name,
            label: ci.name,
          }));
          setCities(allCities);

          if (userDetails.city) {
            setValue('city', { value: userDetails.city, label: userDetails.city });
          }
        }
      }
    }
  }, [UserProfile, setValue]);

  const handleUserProfileEdition = async (data: any) => {
    const formData = new FormData();
    formData.append('name', data?.name);
    formData.append('phonenumber', data?.phonenumber);
    formData.append('address', data?.country?.value);
    formData.append('state', data?.state?.value);
    formData.append('city', data?.city?.value);
    if (image && typeof image !== 'string') {
      formData.append('image', image);
    }

    try {
      const response: any = await EditUserProfile({ body: formData, token }).unwrap();
      if (response?.status) {
        toast.success('Profile updated successfully');
        router.push('/admin/profile');
        refetch();
      }
    } catch (err: any) {
      toast.error(err?.data?.message || 'Error updating profile');
    }
  };

  return (
    <WebsiteLayout>
      <div className="edit-profile">
        <form onSubmit={handleSubmit(handleUserProfileEdition)}>
          <Container fluid>
            <Row className="justify-content-center">
              <Col lg="8">
                <h1 className="heading text-center">Edit Profile</h1>

                <Row className="justify-content-center">
                  <ProfilePictureUpload
                    id="upAvatar"
                    name="upAvatar"
                    label=""
                    onChange={setImage}
                    image={image}
                  />

                  <Col lg="6">
                    <label>Full Name</label>
                    <input
                      placeholder="John Smith"
                      {...register('name')}
                      className="form-control"
                    />
                  </Col>

                  <Col lg="6">
                    <label>Phone Number</label>
                    <input
                      placeholder="+23 1234 12345"
                      {...register('phonenumber')}
                      className="form-control"
                    />
                  </Col>
                </Row>

                <Row className="mt-3">
                  <Col lg="6">
                    <label>Country</label>
                    <Controller
                      name="country"
                      control={control}
                      render={({ field }) => (
                        <Select
                          {...field}
                          options={countries}
                          styles={customStyles}
                          placeholder="Select Country"
                        />
                      )}
                    />
                  </Col>

                  <Col lg="3">
                    <label>State</label>
                    <Controller
                      name="state"
                      control={control}
                      render={({ field }) => (
                        <Select
                          {...field}
                          options={states}
                          styles={customStyles}
                          placeholder="Select State"
                        />
                      )}
                    />
                  </Col>

                  <Col lg="3" className="">
                    <label>City</label>
                    <Controller
                      name="city"
                      control={control}
                      render={({ field }) => (
                        <Select
                          {...field}
                          options={cities}
                          styles={customStyles}
                          placeholder="Select City"
                        />
                      )}
                    />
                  </Col>
                </Row>

                <div className="text-center mt-4">
                  <button type="submit" className="btn btn-primary w-50">
                  {isLoading? <Spinner size='sm'/> : "Update"}
                  </button>
                </div>
              </Col>
            </Row>
          </Container>
        </form>
      </div>
    </WebsiteLayout>
  );
}
