'use client';

import { useState, use, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import {  z } from 'zod';
import Link from 'next/link';
import Image from 'next/image';
import { signIn, getSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import './signup.css';

import { getCountryDataByDomain } from '@/lib/countries';

const signupSchema = z.object({
  email: z.string().email('Invalid email address'),
  password: z.string().min(8, 'Password must be at least 8 characters'),
  confirmPassword: z.string(),
  firstName: z.string().min(2, 'First name must be at least 2 characters'),
  lastName: z.string().min(2, 'Last name must be at least 2 characters'),
  phoneNumber: z.string().min(10, 'Phone number must be at least 10 digits'),
  zipCode: z.string().min(4, 'Zip code must be at least 4 characters'),
  city: z.string().optional(),
  // country: z.string().min(1, 'Please select a canton'),
  role: z.enum(['CLIENT', 'FREELANCER'])
}).refine((data) => data.password === data.confirmPassword, {
  message: "Passwords don't match",
  path: ["confirmPassword"],
});

type SignupFormData = z.infer<typeof signupSchema>;

// interface Country {
//   id: string;
//   name: string;
//   code: string;
// }

interface SignupPageProps {
  params: Promise<{
    locale: string;
  }>;
}

export default function SignupPage({ params }: SignupPageProps) {
  const { locale } = use(params);
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [selectedRole, setSelectedRole] = useState<'CLIENT' | 'FREELANCER'>('CLIENT');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
 // const [countries, setCountries] = useState<Country[]>([]);
  // const [loadingCountries, setLoadingCountries] = useState(true);

  const {
    register,
    handleSubmit,
    formState: { errors },
    setValue
  } = useForm<SignupFormData>({
    resolver: zodResolver(signupSchema),
    defaultValues: {
      role: 'CLIENT',
      // country: 'switzerland'
    }
  });

  // useEffect(() => {
  //   const fetchCountries = async () => {
  //     try {
  //       const response = await fetch('/api/countries');
  //       const data = await response.json();
  //       setCountries(data.countries);
        
  //       // Set Switzerland as default if available
  //       const switzerlandCountry = data.countries.find((country: Country) => 
  //         country.name.toLowerCase() === 'switzerland' || country.code.toLowerCase() === 'ch'
  //       );
  //       if (switzerlandCountry) {
  //         setValue('country', switzerlandCountry.id);
  //       }
  //     } catch (error) {
  //       console.error('Error fetching countries:', error);
  //     } finally {
  //       setLoadingCountries(false);
  //     }
  //   };
  //   fetchCountries();
  // }, [setValue]);

  const onSubmit = async (data: SignupFormData) => {
    setIsLoading(true);
    setError('');

    const datacounter =    getCountryDataByDomain();
    if(!datacounter?.id){
        setError('Country is missing');
        setIsLoading(false);
    }
    try {
      const response = await fetch('/api/auth/signup', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: data.email,
          password: data.password,
          firstName: data.firstName,
          lastName: data.lastName,
          phoneNumber: data.phoneNumber,
          zipCode: data.zipCode,
          city: data.city,
          // country: data.country,
          country: datacounter?.id,
          role: data.role,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || 'Signup failed');
      }

      // Auto-login after successful signup
      const result = await signIn('credentials', {
        email: data.email,
        password: data.password,
        redirect: false,
      });

      if (result?.error) {
        throw new Error('Login failed after signup');
      }

      // Redirect to appropriate page
      const session = await getSession();
      if (session?.user) {
        const role = session.user.role.toLowerCase();
        if (role === 'client') {
          router.push(`/${locale}/client/my-projects`);
        } else {
          router.push(`/${locale}/freelancer/my-projects`);
        }
      }
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Something went wrong';
      setError(message);
    } finally {
      setIsLoading(false);
    }
  };

  const handleRoleSelection = (role: 'CLIENT' | 'FREELANCER') => {
    setSelectedRole(role);
    setValue('role', role);
  };

  return (
    <section className="login-wrapper py-60">
      <div className="container">
        <div className="row">
          <div className="col-12 col-md-6">
            <div className="title">
              <h1>
                Join as a client or freelancer
              </h1>
            </div>
            <div className="discription">
              <p>
                Set up your profile to get better matches and smoother hiring or freelancing on Smile24.
              </p>
            </div>
            <div className="signup-client-type mb-2">
              <ul>
                <li>
                  <button 
                    type="button"
                    onClick={() => handleRoleSelection('CLIENT')}
                    className={`link-type ${selectedRole === 'CLIENT' ? 'active' : ''}`}
                  >
                    <div className="img-box">
                      <Image 
                        src="/assets/image/hiring.svg" 
                        className="icon" 
                        alt="hiring"
                        width={0}
                        height={0}
                        sizes="100vw"
                        style={{ width: 'auto', height: 'auto' }}
                      />
                    </div>
                    <div className="content">
                      <h5>
                        I&apos;m a client, ready to hire
                      </h5>
                      <p>
                        Let&apos;s find the right freelancer for your next project — fast and easy.
                      </p>
                    </div>
                  </button>
                </li>
                <li>
                  <button 
                    type="button"
                    onClick={() => handleRoleSelection('FREELANCER')}
                    className={`link-type ${selectedRole === 'FREELANCER' ? 'active' : ''}`}
                  >
                    <div className="img-box">
                      <Image 
                        src="/assets/image/userhr.svg" 
                        className="icon" 
                        alt="profie user"
                        width={0}
                        height={0}
                        sizes="100vw"
                        style={{ width: 'auto', height: 'auto' }}
                      />
                    </div>
                    <div className="content">
                      <h5>
                        I&apos;m a freelancer, looking for work
                      </h5>
                      <p>
                        Show off your skills and get discovered by the right clients.
                      </p>
                    </div>
                  </button>
                </li>
              </ul>
            </div>
          </div>
          <div className="col-12 col-md-6">
            <div className="login-form">
              <div className="signup-head">
                <h2>
                  Welcome to Smile24 as a {selectedRole === 'CLIENT' ? 'Client' : 'Freelancer'}
                </h2>
                <div className="discription">
                  <p>
                    Quickly polish your profile for better results.
                  </p>
                </div>
              </div>
              <div className="form-wrap signup-form-wrap">
                <form onSubmit={handleSubmit(onSubmit)}>
                  {error && (
                    <div className="alert alert-danger" role="alert">
                      {error}
                    </div>
                  )}
                  
                  <div className="form-group">
                    <div className="mb-20">
                      <label htmlFor="firstname" className="form-label">First Name</label>
                      <div className="input-icon">
                        <Image 
                          src="/assets/image/user.svg" 
                          className="icon" 
                          alt="user"
                          width={0}
                          height={0}
                          sizes="100vw"
                          style={{ width: 'auto', height: 'auto' }}
                        />
                        <input 
                          type="text" 
                          className={`form-control ${errors.firstName ? 'is-invalid' : ''}`}
                          id="firstname" 
                          placeholder="First Name"
                          {...register('firstName')}
                          disabled={isLoading}
                        />
                      </div>
                      {errors.firstName && (
                        <div className="form-text error-text">{errors.firstName.message}</div>
                      )}
                    </div>
                    <div className="mb-20">
                      <label htmlFor="lastname" className="form-label">Last Name</label>
                      <div className="input-icon">
                        <Image 
                          src="/assets/image/user.svg" 
                          className="icon" 
                          alt="user"
                          width={0}
                          height={0}
                          sizes="100vw"
                          style={{ width: 'auto', height: 'auto' }}
                        />
                        <input 
                          type="text" 
                          className={`form-control ${errors.lastName ? 'is-invalid' : ''}`}
                          id="lastname" 
                          placeholder="Last Name"
                          {...register('lastName')}
                          disabled={isLoading}
                        />
                      </div>
                      {errors.lastName && (
                        <div className="form-text error-text">{errors.lastName.message}</div>
                      )}
                    </div>
                  </div>

                  <div className="form-group">
                    <div className="mb-20">
                      <label htmlFor="Email" className="form-label">Email Address</label>
                      <div className="input-icon">
                        <Image 
                          src="/assets/image/email.svg" 
                          className="icon" 
                          alt="email"
                          width={0}
                          height={0}
                          sizes="100vw"
                          style={{ width: 'auto', height: 'auto' }}
                        />
                        <input 
                          type="email" 
                          className={`form-control ${errors.email ? 'is-invalid' : ''}`}
                          id="Email" 
                          placeholder="Email Address"
                          {...register('email')}
                          disabled={isLoading}
                        />
                      </div>
                      {errors.email && (
                        <div className="form-text error-text">{errors.email.message}</div>
                      )}
                    </div>
                    <div className="mb-20">
                      <label htmlFor="number" className="form-label">Phone Number</label>
                      <div className="input-icon">
                        <Image 
                          src="/assets/image/phone.svg" 
                          className="icon" 
                          alt="phone"
                          width={0}
                          height={0}
                          sizes="100vw"
                          style={{ width: 'auto', height: 'auto' }}
                        />
                        <input 
                          type="tel" 
                          className={`form-control ${errors.phoneNumber ? 'is-invalid' : ''}`}
                          id="number" 
                          placeholder="Phone Number"
                          {...register('phoneNumber')}
                          disabled={isLoading}
                        />
                      </div>
                      {errors.phoneNumber && (
                        <div className="form-text error-text">{errors.phoneNumber.message}</div>
                      )}
                    </div>
                  </div>
                  
                  <div className="form-group no-icon-box">
                    <div className="mb-20">
                      <label htmlFor="zipcode" className="form-label">Zip Code</label>
                      <div className="input-icon">
                        <input 
                          type="text" 
                          className={`form-control ${errors.zipCode ? 'is-invalid' : ''}`}
                          id="zipcode" 
                          placeholder="Zip Code"
                          {...register('zipCode')}
                          disabled={isLoading}
                        />
                      </div>
                      {errors.zipCode && (
                        <div className="form-text error-text">{errors.zipCode.message}</div>
                      )}
                    </div>
                    <div className="mb-20">
                      <label htmlFor="city" className="form-label">City</label>
                      <div className="input-icon">
                        <input 
                          type="text" 
                          className="form-control" 
                          id="city" 
                          placeholder="Enter City" 
                          {...register('city')}
                          disabled={isLoading}
                        />
                      </div>
                    </div>
                    {/* <div className="mb-20 no-icon-box">
                      <label htmlFor="country" className="form-label">Country</label>
                      <div className="input-icon">
                        <select 
                          className={`form-control ${errors.country ? 'is-invalid' : ''}`}
                          id="country" 
                          {...register('country')}
                          disabled={isLoading || loadingCountries}
                        >
                          <option value="">Select Country</option>
                          {countries.map((country) => (
                            <option key={country.id} value={country.id}>
                              {country.name}
                            </option>
                          ))}
                        </select>
                      </div>
                      {errors.country && (
                        <div className="form-text error-text">{errors.country.message}</div>
                      )}
                    </div> */}
                  </div>

                  <div className="form-group">
                    <div>
                      <label htmlFor="Password" className="form-label">Password</label>
                      <div className="input-icon">
                        <Image 
                          src="/assets/image/lock.svg" 
                          className="icon" 
                          alt="password"
                          width={0}
                          height={0}
                          sizes="100vw"
                          style={{ width: 'auto', height: 'auto' }}
                        />
                        <input 
                          type={showPassword ? 'text' : 'password'}
                          className={`form-control ${errors.password ? 'is-invalid' : ''}`}
                          id="Password" 
                          placeholder="Enter Password"
                          {...register('password')}
                          disabled={isLoading}
                        />
                        <div 
                          className="password-show-hide"
                          onClick={() => setShowPassword(!showPassword)}
                        >
                          {/* <Image 
                            src="/assets/image/eye.svg" 
                            className="icon" 
                            alt="password"
                            width={0}
                            height={0}
                            sizes="100vw"
                            style={{ width: 'auto', height: 'auto' }}
                          /> */}

                          <Image 
                              src={showPassword ? "/assets/image/eye-slash.svg" : "/assets/image/eye.svg"} 
                              className="icon" 
                              alt={showPassword ? "hide password" : "show password"}
                              width={24}
                              height={24}
                            />
                        </div>
                      </div>
                      {errors.password && (
                        <div className="form-text error-text">{errors.password.message}</div>
                      )}
                    </div>

                    <div>
                      <label htmlFor="confirmpassword" className="form-label">Confirm Password</label>
                      <div className="input-icon">
                        <Image 
                          src="/assets/image/lock.svg" 
                          className="icon" 
                          alt="confirmpassword"
                          width={0}
                          height={0}
                          sizes="100vw"
                          style={{ width: 'auto', height: 'auto' }}
                        />
                        <input 
                          type={showConfirmPassword ? 'text' : 'password'}
                          className={`form-control ${errors.confirmPassword ? 'is-invalid' : ''}`}
                          id="confirmpassword" 
                          placeholder="Enter Confirm Password"
                          {...register('confirmPassword')}
                          disabled={isLoading}
                        />
                        <div 
                          className="password-show-hide"
                          onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                        >
                          <Image 
                            src="/assets/image/eye.svg" 
                            className="icon" 
                            alt="password"
                            width={0}
                            height={0}
                            sizes="100vw"
                            style={{ width: 'auto', height: 'auto' }}
                          />
                        </div>
                      </div>
                      {errors.confirmPassword && (
                        <div className="form-text error-text">{errors.confirmPassword.message}</div>
                      )}
                    </div>
                  </div>
                  
                  <input type="hidden" {...register('role')} value={selectedRole} />
                  
                  <button 
                    type="submit" 
                    className="w-100 custom-btn secondary-btn"
                    disabled={isLoading}
                  >
                    {isLoading ? 'Signing Up...' : 'Sign Up'}
                  </button>
                </form>
                <div className="form-sub-box">
                  <p>
                    Already Have an Account?{' '}
                    <Link href={`/${locale}/login`} className="primary-text">
                      Login Now
                    </Link>
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
} 
