import { useContext, useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { AuthContext } from "@/helpers/context/AuthProvider";
import { APP_BASE_URL } from "@/utils/constants";
import { fetchHeader } from "@/helpers/fetch.helper";
import { useToast } from "@/hooks/use-toast";
import { getEduConnectAccessToken } from "@/helpers/token.helper";
import { Loader } from "lucide-react";

const UserTabContent = () => {

  const { user , fetchUser } = useContext(AuthContext);
  const { toast } = useToast();
  const [loading , setLoading] = useState<boolean>(false)
  // Centralized state for all form inputs
  const [inputValues, setInputValues] = useState({
    profile_picture: user?.profile_picture,
    firstName: user?.firstName,
    lastName: user?.lastName,
    username: user?.username,
    dob: user?.dob,
    bio: user?.bio,
  });
  const [error , setError] = useState<Record<string,any>>({})

  // Handle input changes for text, date, and textarea fields
  const handleInputChange = (field: string, value: string) => {
    setInputValues((prev) => ({
      ...prev,
      [field]: value,
    }));
  };

  // Function to handle profile picture upload
  const handleUploadPicture = async(event: React.ChangeEvent<HTMLInputElement>) : Promise<void> => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = () => {
        setInputValues((prev) => ({
          ...prev,
          profile_picture: reader.result as string,
        }));
      };
      const formData = new FormData();
      formData.append('profile_picture' , file !)
      try{
        const res = await fetch(APP_BASE_URL + '/api/profile/update-profile-picture' , {
          headers : fetchHeader(),
          method : 'PATCH',
          body : formData
        })
        const data = await res.json()
        if(res.status == 200){
          toast({
            title : 'Sucessfully updated profile picture',
            description : `${data?.message}`,
            variant : 'success'
          })
          fetchUser(getEduConnectAccessToken() !)
        }else{
          toast({
            title : 'Error updatingprofile image',
            description : `${data?.message}`,
            variant : 'destructive'
          })
        }
      }catch(error:any){
        toast({
          title : 'Error updatingprofile image',
          description : `${error?.message}`,
          variant : 'destructive'
        })
      }
      reader.readAsDataURL(file);
    }
  };

  // Function to handle the Save Changes button click
  const handleSaveChanges = async()  :Promise<void> => {
    
    setLoading(true);
    setError({});

    const formData = new FormData();

    Object.entries(inputValues).forEach(([key, value] : [key : string , value : any]) => {
      if(key == 'profile_picture'){
        if(value instanceof File){
          formData.append(key, value);
        }
      }else{
        formData.append(key, value);
      }
    });

    try{
      const res = await fetch(APP_BASE_URL + '/api/profile/me' , {
        headers : fetchHeader(),
        body : formData,
        method : 'PUT'
      })
      const data = await res.json()
      if(res.status == 200){
        toast({
          title : 'Sucessfully Updated profile',
          description : `${data?.message}`,
          variant : 'success'
        })
        fetchUser(getEduConnectAccessToken() !)
      }else{
        toast({
          title : 'Error updating profile',
          description : `${data?.error}`,
          variant : 'success'
        })
      }
    }catch(e : any){
      toast({
        title : 'Sucessfully Updated profile',
        description : `${error?.message}`,
        variant : 'success'
      })
    }finally{
      setLoading(false)
    }
  };

  useEffect(() => {
    setInputValues(
      {
        profile_picture: user?.profile_picture,
        firstName: user?.firstName,
        lastName: user?.lastName,
        username: user?.username,
        dob: user?.dob?.split('T')?.at(0),
        bio: user?.bio,
      }
    )
  },[user])

  return (
    <Card>
      <CardHeader>
        <CardTitle>Profile</CardTitle>
        <p className="text-sm text-gray-500">
          Manage your personal information and profile settings.
        </p>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* Profile Picture */}
        <div className="space-y-2">
          <label className="text-sm font-medium">Profile Picture</label>
          <div className="flex items-center gap-4">
            <div className="h-16 w-16 rounded-full bg-gray-100 flex items-center justify-center">
              {inputValues.profile_picture ? (
                <img
                  src={inputValues.profile_picture}
                  alt="Profile"
                  className="h-16 w-16 rounded-full object-cover"
                />
              ) : (
                <span className="text-gray-500 text-sm">No image</span>
              )}
            </div>
            <div>
                <Button variant="outline" asChild>
                  <label htmlFor="profile_pictureUpload" className="cursor-pointer">
                    Upload Image
                  </label>
                </Button>
              <input
                id="profile_pictureUpload"
                type="file"
                accept="image/*"
                onChange={handleUploadPicture}
                className="hidden"
              />
            </div>
          </div>
        </div>

        {/* Name */}
        <div className="grid grid-cols-2 gap-4">
          <div className="space-y-2">
            <label className="text-sm font-medium">First Name</label>
            <Input
              value={inputValues?.firstName}
              onChange={(e) => handleInputChange("firstName", e.target.value)}
            />
          </div>
          <div className="space-y-2">
            <label className="text-sm font-medium">Last Name</label>
            <Input
              value={inputValues?.lastName}
              onChange={(e) => handleInputChange("lastName", e.target.value)}
            />
          </div>
        </div>

        {/* Username */}
        <div className="grid grid-cols-2 gap-4">
          <div className="space-y-2">
            <label className="text-sm font-medium">Username</label>
            <Input
              value={inputValues?.username}
              onChange={(e) => handleInputChange("username", e.target.value)}
              error={error?.username}
            />
            <p className="text-sm text-gray-500">
              This is your public display name. You can only change this once
              every 30 days.
            </p>
          </div>
          <div className="space-y-2">
            <label className="text-sm font-medium">Date of Birth</label>
            <Input
              type="date"
              value={inputValues?.dob}
              onChange={(e) => handleInputChange("dob", e.target.value)}
              error={error?.dob}
            />
          </div>
        </div>

        {/* Bio */}
        <div className="space-y-2">
          <label className="text-sm font-medium">Bio</label>
          <Textarea
            value={inputValues?.bio}
            onChange={(e) => handleInputChange("bio", e.target.value)}
            placeholder="Tell us about yourself"
          />
          <p className="text-sm text-gray-500">
            You can @mention other users and organizations to link to them.
          </p>
          {
            error?.bio && error?.bio?.map((err : string , key : number) => {
              return(
                <span key={key}>{err}</span>
              )
            })
          }
        </div>

        {/* Save Changes Button */}
        <div className="mx-auto w-fit">
          <Button
            className="mt-6 w-full md:min-w-[600px] min-w-[300px] bg-purple-700"
            onClick={handleSaveChanges}
          >
            {
              loading 
              ? 
                <>
                <Loader className="w-4 h-4"/>
                Saving changes
                </> 
              : 'Save Changes'
            }
            
          </Button>
        </div>
      </CardContent>
    </Card>
  );
};

export default UserTabContent;
