import { useState, useEffect } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { Country, State, City } from 'country-state-city';
import { Form, Spinner } from 'react-bootstrap';

import { ImageUploader, Textarea, Textinput } from '@/components';
import CustomSelect from '@/components/Form/Select';
import Button from '@/components/ui/Button';
import { useCreateProfileMutation } from '@/lib/redux/services/auth.api';
import { useSelector } from 'react-redux';
import errorHandler from '@/utils/request/errorHandler';
import { useSession } from 'next-auth/react';
import { getFormData } from '@/utils';
import toast from 'react-hot-toast';

const CreateProfile = () => {
  const router = useRouter();
  const [createProfile, { isLoading }] = useCreateProfileMutation();
  const { data: session, update } = useSession();

  const [formData, setFormData] = useState({
    full_name: '',
    phone_number: '',
    address: '',
    dob: '',
    gender: '',
  });

  const [selectedCountry, setSelectedCountry] = useState<any>(null);
  const [selectedState, setSelectedState] = useState<any>(null);
  const [selectedCity, setSelectedCity] = useState<any>(null);
  const [image, setImage] = useState<File | null>(null);

  const [stateOptions, setStateOptions] = useState<any[]>([]);
  const [cityOptions, setCityOptions] = useState<any[]>([]);

  useEffect(() => {
    if (selectedCountry) {
      const states = State.getStatesOfCountry(selectedCountry.isoCode);
      setStateOptions(states);
      setSelectedState(null);
      setCityOptions([]);
    }
  }, [selectedCountry]);

  useEffect(() => {
    if (selectedState) {
      const cities = City.getCitiesOfState(selectedState.countryCode, selectedState.isoCode);
      setCityOptions(cities);
    }
  }, [selectedState]);

  const handleChange = (field: string, value: any) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleSubmit = async () => {
    const formDataIns = new FormData();
    const formDataPayload = getFormData(formData, formDataIns);

    formDataPayload.append('country', selectedCountry?.name || '');
    formDataPayload.append('state', selectedState?.name || '');
    formDataPayload.append('city', selectedCity?.name || '');
    if (image) formDataIns.append('image', image);

    try {
      const token = session?.user?.token;
      if (!token) {
        toast.error('Token not found. Please try again.');
        return;
      }

      await createProfile({ body: formDataPayload, token }).unwrap().then(async (res) => {
        if (res.success) {
          await update({ user: res.data });
          toast.success("Profile Updated Successfully");
          if (res.data.data.userType === "carrier") {
            router.push('/auth/create-professional-account');
          } else {
            router.push('/user');
          }
        } else {
          return errorHandler(res);
        }
      }).catch((err) => {
        return errorHandler(err);
      });

    } catch (error) {
      errorHandler(error);
    }
  };

  return (
    <>
      <Head>
        <title>Create Account | Deliver X</title>
      </Head>

      {/* Full-screen loading overlay */}
      {isLoading && (
        <div className="position-fixed top-0 start-0 w-100 h-100 d-flex justify-content-center align-items-center bg-white bg-opacity-75" style={{ zIndex: 9999 }}>
          <Spinner animation="border" variant="primary" role="status" />
        </div>
      )}

      <div className="h-100 overflow-y-auto pb-5 pt-15 d-flex flex-column justify-content-center align-items-center">
        <h2 className="display-6 fw-bolder">Create Account</h2>
        <p>Please enter your details to Create account</p>
        <div className="w-100">

          <ImageUploader onChange={(file: File) => setImage(file)} />

          <Form.Group className="mt-4">
            <Form.Label>Full Name</Form.Label>
            <Textinput
              iconLeft={<img src="/images/icons/user-icon.png" />}
              type="text"
              placeholder="John Smith"
              onChange={(e) => handleChange('full_name', e.target.value)}
            />
          </Form.Group>

          <Form.Group className="mt-4">
            <Form.Label>Phone Number</Form.Label>
            <Textinput
              iconLeft={<img src="/images/icons/phone-icon.png" />}
              type="text"
              placeholder="+123 456 7890"
              onChange={(e) => handleChange('phone_number', e.target.value)}
            />
          </Form.Group>

          <Form.Group className="mt-4">
            <Form.Label>Address</Form.Label>
            <Textarea
              iconLeft={<img src="/images/icons/location.png" />}
              placeholder="Enter address"
              onChange={(e) => handleChange('address', e.target.value)}
            />
          </Form.Group>

          <Form.Group className="mt-4">
            <Form.Label>Gender</Form.Label>
            <Textinput
              iconLeft={<img src="/images/icons/location.png" />}
              placeholder="Enter gender"
              onChange={(e) => handleChange('gender', e.target.value)}
            />
          </Form.Group>

          <Form.Group className="mt-4">
            <Form.Label>Date of Birth</Form.Label>
            <Textinput
              iconLeft={<img src="/images/icons/location.png" />}
              placeholder="Enter dob"
              onChange={(e) => handleChange('dob', e.target.value)}
            />
          </Form.Group>

          <CustomSelect
            label="Country"
            icon={<img src="/images/icons/country.png" />}
            defaultValue={selectedCountry}
            options={Country.getAllCountries().map((country) => ({
              value: country.isoCode,
              label: country.name,
              countryData: country,
            }))}
            onChange={(option: any) => setSelectedCountry(option.countryData)}
          />

          <CustomSelect
            label="State"
            icon={<img src="/images/icons/state.png" />}
            defaultValue={selectedState}
            options={stateOptions.map((state) => ({
              value: state.isoCode,
              label: state.name,
              stateData: state,
            }))}
            onChange={(option: any) => setSelectedState(option.stateData)}
            isDisabled={!selectedCountry}
          />

          <CustomSelect
            label="City"
            icon={<img src="/images/icons/building.png" />}
            defaultValue={selectedCity}
            options={cityOptions.map((city) => ({
              value: city.name,
              label: city.name,
              cityData: city,
            }))}
            onChange={(option: any) => setSelectedCity(option.cityData)}
            isDisabled={!selectedState}
          />

          <div className="d-flex justify-content-center align-items-center">
            <Button
              onClick={handleSubmit}
              type="submit"
              size="md"
              className="mt-5 btn btn-feature auth-btn"
              disabled={isLoading}
            >
              {isLoading ? (
                <>
                  <Spinner animation="border" size="sm" role="status" className="me-2" />
                  Creating...
                </>
              ) : (
                'Create Account'
              )}
            </Button>
          </div>
        </div>
      </div>
    </>
  );
};

export default CreateProfile;
