import { FormEvent, useContext, useEffect, useState } from 'react';
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { EyeIcon, EyeOffIcon, Upload, X } from 'lucide-react';
import Link from 'next/link';
import { routes } from '@/lib/routes';
import { useToast } from '@/hooks/use-toast';
import { AuthContext } from '@/helpers/context/AuthProvider';
import { setEduConnectAccessToken } from '@/helpers/token.helper';
import { useRouter } from 'next/navigation';

export default function SignupForm() {
  const router = useRouter();
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [inputValues, setInputValues] = useState({
    email: '',
    firstName: '',
    lastName: '',
    username: '',
    password: '',
    bio: '',
    dob: '',
    profile_picture: null as File | null
  });
  const [error, setError] = useState<Record<string, any>>({});

  const { fetchUser, user } = useContext(AuthContext);
  const { toast } = useToast();

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { id, value } = e.target;
    setInputValues(prev => ({
      ...prev,
      [id]: value
    }));
  };

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 5 * 1024 * 1024) {
        setError(prev => ({
          ...prev,
          profile_picture: ['File size should be less than 5MB']
        }));
        return;
      }
      if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
        setError(prev => ({
          ...prev,
          profile_picture: ['Please upload an image file (JPG, PNG, or GIF)']
        }));
        return;
      }
      
      // Create preview URL
      const objectUrl = URL.createObjectURL(file);
      setPreviewUrl(objectUrl);
      
      setInputValues(prev => ({
        ...prev,
        profile_picture: file
      }));
      
      // Clear any existing errors
      setError(prev => ({
        ...prev,
        profile_picture: null
      }));
    }
  };

  const removeImage = () => {
    setInputValues(prev => ({
      ...prev,
      profile_picture: null
    }));
    if (previewUrl) {
      URL.revokeObjectURL(previewUrl);
      setPreviewUrl(null);
    }
  };

  const handleSubmit = async(e : FormEvent<HTMLFormElement>) : Promise<void> => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget)
    Object.entries(inputValues).forEach(([key, value]) => {
      if(value){
        formData.append(key, value);
      }
    });

    try{
      const res = await fetch(`${process.env.NEXT_PUBLIC_EDU_CONNECT_HOST}/api/profile/register` , {
        method : 'POST' , 
        body : formData
      })
      
      const data : any = await res.json();

      if(res.status == 201){
        toast({
          title : 'Sucessfully registered in !',
          description : `${data?.message}`,
          variant : 'success'
        })

        setInputValues({
          email: '',
          firstName: '',
          lastName: '',
          username: '',
          password: '',
          bio: '',
          dob: '',
          profile_picture: null as File | null
        })
        
        router.push(routes.LOGIN_ROUTES)
      }else{
        setError(data?.error)
        toast({
          title : 'Error signing in !',
          description : `${data?.error}`,
          variant : 'destructive'
        })
      }
    }catch(e : any){
      toast({
        title : 'Error signing in !',
        description : `${error?.message}`,
        variant : 'destructive'
      })
    }finally{
      setLoading(false)
    }
  }

  // Clean up preview URL when component unmounts
  useEffect(() => {
    return () => {
      if (previewUrl) {
        URL.revokeObjectURL(previewUrl);
      }
    };
  }, [previewUrl]);

  return (
    <div className="flex items-center justify-center min-h-[80vh]">
      <Card className="w-full max-w-lg shadow-lg border border-purple-700">
        <CardHeader className="space-y-3">
          <CardTitle className="text-2xl font-bold text-purple-600">Create Account</CardTitle>
          <CardDescription className="text-gray-600">
            Fill in your details to create your account
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2 col-span-2">
                <Label htmlFor="profile_picture" className="text-gray-700">Profile Picture</Label>
                <div className="space-y-4">
                  {previewUrl ? (
                    <div className="relative w-32 h-32 mx-auto">
                      <img
                        src={previewUrl}
                        alt="Profile preview"
                        className="w-full h-full object-cover rounded-full"
                      />
                      <button
                        type="button"
                        onClick={removeImage}
                        className="absolute -top-2 -right-2 p-1 bg-red-500 text-white rounded-full hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
                      >
                        <X className="h-4 w-4" />
                      </button>
                    </div>
                  ) : (
                    <div className="flex items-center justify-center">
                      <div className="w-32 h-32 bg-gray-100 rounded-full flex items-center justify-center">
                        <Upload className="h-8 w-8 text-gray-400" />
                      </div>
                    </div>
                  )}
                  <div className="flex items-center justify-center space-x-2">
                    <Button
                      type="button"
                      variant="outline"
                      className="h-11 px-4 border-gray-200 hover:bg-gray-50"
                      onClick={() => document.getElementById('profile_picture_input')?.click()}
                    >
                      <Upload className="h-5 w-5 mr-2" />
                      {previewUrl ? 'Change Photo' : 'Upload Photo'}
                    </Button>
                    <input
                      id="profile_picture_input"
                      type="file"
                      accept="image/*"
                      className="hidden"
                      onChange={handleFileUpload}
                    />
                  </div>
                  {error?.profile_picture && (
                    <p className="text-sm text-red-500 text-center">{error.profile_picture}</p>
                  )}
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="firstName" className="text-gray-700">First Name</Label>
                <Input 
                  id="firstName"
                  value={inputValues.firstName}
                  onChange={handleInputChange}
                  className={`h-11 px-4 bg-gray-50/50 border-gray-200 focus:border-purple-500 focus:ring-purple-500 ${
                    error?.firstName ? 'border-red-500' : ''
                  }`}
                  placeholder="Enter your first name"
                  error={error?.firstName}
                />
                
              </div>

              <div className="space-y-2">
                <Label htmlFor="lastName" className="text-gray-700">Last Name</Label>
                <Input 
                  id="lastName"
                  value={inputValues.lastName}
                  onChange={handleInputChange}
                  className={`h-11 px-4 bg-gray-50/50 border-gray-200 focus:border-purple-500 focus:ring-purple-500 ${
                    error?.lastName ? 'border-red-500' : ''
                  }`}
                  placeholder="Enter your last name"
                  error={error?.lastName}
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="email" className="text-gray-700">Email</Label>
              <Input 
                id="email"
                type="email"
                value={inputValues.email}
                onChange={handleInputChange}
                className={`h-11 px-4 bg-gray-50/50 border-gray-200 focus:border-purple-500 focus:ring-purple-500 ${
                  error?.email ? 'border-red-500' : ''
                }`}
                placeholder="Enter your email"
                error={error?.email}
              />
              
            </div>

            <div className="space-y-2">
              <Label htmlFor="username" className="text-gray-700">Username</Label>
              <Input 
                id="username"
                value={inputValues?.username}
                onChange={handleInputChange}
                className={`h-11 px-4 bg-gray-50/50 border-gray-200 focus:border-purple-500 focus:ring-purple-500 ${
                  error?.username ? 'border-red-500' : ''
                }`}
                placeholder="Choose a username"
                error={error?.username}
              />
              
            </div>

            <div className="space-y-2">
              <Label htmlFor="password" className="text-gray-700">Password</Label>
              <div className="relative">
                <Input 
                  id="password"
                  type={showPassword ? "text" : "password"}
                  value={inputValues.password}
                  onChange={handleInputChange}
                  className={`h-11 px-4 bg-gray-50/50 border-gray-200 focus:border-purple-500 focus:ring-purple-500 pr-10 ${
                    error?.password ? 'border-red-500' : ''
                  }`}
                  placeholder="Create a strong password"
                  error={error?.password}
                />
                
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="dob" className="text-gray-700">Date of Birth</Label>
              <Input 
                id="dob"
                type="date"
                value={inputValues.dob}
                onChange={handleInputChange}
                className={`h-11 px-4 bg-gray-50/50 border-gray-200 focus:border-purple-500 focus:ring-purple-500 ${
                  error?.dob ? 'border-red-500' : ''
                }`}
                error={error?.firstName}
              />
              
            </div>

            <div className="space-y-2">
              <Label htmlFor="bio" className="text-gray-700">Bio</Label>
              <textarea 
                id="bio"
                value={inputValues.bio}
                onChange={handleInputChange}
                className={`w-full px-4 py-2 bg-gray-50/50 border-gray-200 rounded-md focus:border-purple-500 focus:ring-purple-500 ${
                  error?.bio ? 'border-red-500' : ''
                }`}
                rows={3}
                placeholder="Tell us about yourself"
              />
              {error?.bio && (
                <p className="text-sm text-red-500">{error.bio}</p>
              )}
            </div>

            <Button 
              type="submit" 
              className="w-full h-11 bg-purple-600 hover:bg-purple-700 text-white font-semibold disabled:opacity-50"
              disabled={loading}
            >
              {loading ? 'Creating Account...' : 'Create Account'}
            </Button>

            <div className="text-center text-sm text-gray-600">
              Already have an account?{' '}
              <Link href={routes.LOGIN_ROUTES} className="text-purple-600 hover:text-purple-700 font-semibold">
                Login
              </Link>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}