import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import PhoneInput from 'react-phone-input-2';
import 'react-phone-input-2/lib/style.css';
import { useForm, Controller } from 'react-hook-form';
import LoadingSpinner from '../components/partials/LoadingSpinner';
import endpoints from '../config/apiEndpoints';
import { toast } from 'react-toastify';

type FormData = {
  phone: string;
  email: string;
  password: string;
  confirm_password: string;
  agree_terms: boolean;
};

const SignUp = () => {
  const {signup: signupApi} = endpoints;
  const [countryCode, setCountryCode] = useState('');
  const [isSigningUp, setIsSigningUp] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [phonePlaceholder, setPhonePlaceholder] = useState('Mobile Number');
  const navigate = useNavigate();

  const { control, handleSubmit, watch, formState: { errors } } = useForm<FormData>({
    defaultValues: {
      phone: '',
      email: '',
      password: '',
      confirm_password: '',
      agree_terms: false
    }
  });

  const password = watch('password');

  const handlePhoneChange = (value: string, country: { iso2: string; dialCode: string }, formChange: (value: string) => void) => {
    setCountryCode(`+${country.dialCode}`);
    formChange(value);
    
    // Set placeholder based on country
    if (country.iso2 === 'bd') {
      setPhonePlaceholder('1XXXXXXXXX');
    } else if (country.iso2 === 'in') {
      setPhonePlaceholder('9XXXXXXXXX');
    } else if (country.iso2 === 'us') {
      setPhonePlaceholder('(XXX) XXX-XXXX');
    } else if (country.iso2 === 'gb') {
      setPhonePlaceholder('7XXXXXXXXXX');
    } else {
      setPhonePlaceholder(`${country.dialCode} XXXXXXXXXX`);
    }
  };
  const onSubmit = async (data: FormData) => {
    setIsSigningUp(true);
    try {
      const response = await fetch(signupApi , {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({
          phone: data.phone,
          country_code: countryCode,
          email: data.email,
          password: data.password,
        }),
      });

      const responseData = await response.json();

      if (responseData?.message) {
        // localStorage.setItem('access_token', responseData.access_token);
        // localStorage.setItem('user', JSON.stringify(responseData.user));

        toast.success(responseData.message[0]);

        // Redirect on success
        navigate('/signin');
      } else {
        setError(responseData.message || 'Login failed.');
      }
    } catch (err) {
        setIsSigningUp(false);
      setError('Something went wrong. Please try again.');
      console.log(err);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center px-4 bg-gray-50">
        {isSigningUp == true ? <LoadingSpinner text="Creating Account" /> : '' }
      <div className="max-w-md w-full space-y-6 bg-white p-10 rounded-xl shadow-2xl border border-gray-100">
        <div>
          <h2 className="text-center text-3xl font-extrabold text-primary">
            Create Your Account
          </h2>
          <p className="mt-2 text-center text-sm text-gray-600">
            Fill out the form to get started.
          </p>
        </div>

        {error && <div className="text-red-500 text-sm text-center p-3 bg-red-50 rounded-lg">{error}</div>}

        <form className="space-y-6" onSubmit={handleSubmit(onSubmit)}>
          <div>
            <label className="block text-sm font-medium text-gray-700">Mobile Number</label>
            <div className="mt-1">
              <Controller
                name="phone"
                control={control}
                rules={{ required: "Phone number is required" }}
                render={({ field: { onChange, value } }) => (
                  <PhoneInput
                    country={'bd'}
                    value={value}
                    onChange={(value, country: { iso2: string; dialCode: string }) => handlePhoneChange(value, country, onChange)}
                    inputProps={{
                      name: 'phone',
                      required: true,
                      className: 'w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary',
                      placeholder: phonePlaceholder,
                      style: { paddingLeft: '50px' }
                    }}
                    containerClass="w-full"
                    buttonStyle={{ 
                      borderTopLeftRadius: '0.375rem', 
                      borderBottomLeftRadius: '0.375rem',
                      width: '47px',
                    }}
                    dropdownStyle={{ width: '300px' }}
                    enableSearch={true}
                    searchPlaceholder="Search country..."
                    searchNotFound="No country found"
                  />
                )}
              />
              {errors.phone && <p className="mt-1 text-xs text-red-500">{errors.phone.message}</p>}
            </div>
          </div>

          <div className="text-center text-sm text-gray-500">or</div>

          <div>
            <label className="block text-sm font-medium text-gray-700">Email Address</label>
            <Controller
              name="email"
              control={control}
              rules={{ 
                required: "Email is required",
                pattern: {
                  value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                  message: "Invalid email address"
                }
              }}
              render={({ field }) => (
                <input
                  type="email"
                  {...field}
                  className="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                  placeholder="Email Address"
                />
              )}
            />
            {errors.email && <p className="mt-1 text-xs text-red-500">{errors.email.message}</p>}
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700">Password</label>
              <Controller
                name="password"
                control={control}
                rules={{ 
                  required: "Password is required",
                  minLength: {
                    value: 8,
                    message: "Password must be at least 8 characters"
                  }
                }}
                render={({ field }) => (
                  <input
                    type="password"
                    {...field}
                    className="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                    placeholder="********"
                  />
                )}
              />
              {errors.password && <p className="mt-1 text-xs text-red-500">{errors.password.message}</p>}
              {!errors.password && <p className="mt-1 text-xs text-red-500"></p>}
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700">Confirm password</label>
              <Controller
                name="confirm_password"
                control={control}
                rules={{ 
                  required: "Please confirm your password",
                  validate: value => value === password || "Passwords do not match"
                }}
                render={({ field }) => (
                  <input
                    type="password"
                    {...field}
                    className="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                    placeholder="********"
                  />
                )}
              />
              {errors.confirm_password && <p className="mt-1 text-xs text-red-500">{errors.confirm_password.message}</p>}
            </div>
          </div>

          <div className="flex items-center">
            <Controller
              name="agree_terms"
              control={control}
              rules={{ required: "You must agree to the terms and conditions" }}
              render={({ field: { onChange, onBlur, value, ref } }) => (
                <input
                  id="agree_terms"
                  type="checkbox"
                  onChange={onChange}
                  onBlur={onBlur}
                  checked={value}
                  ref={ref}
                  className="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded"
                />
              )}
            />
            <label htmlFor="agree_terms" className="ml-2 block text-sm text-gray-900">
              By signing up you agree to our <Link to="/terms-and-condition" className="text-primary">terms and conditions</Link>.
            </label>
          </div>
          {errors.agree_terms && <p className="mt-1 text-xs text-red-500">{errors.agree_terms.message}</p>}

          <div>
            <button
              type="submit"
              className="w-full flex justify-center py-2 px-4 border border-transparent rounded-full shadow-sm text-sm font-medium text-white bg-primary hover:bg-pink-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary"
            >
              Create Account
            </button>
          </div>

          <div className="text-center text-sm">
            Already have an account?{' '}
            <Link to="/signin" className="font-medium text-primary hover:text-pink-500">
              Sign in
            </Link>
          </div>
        </form>
      </div>
    </div>
  );
};

export default SignUp;