import React, { useState, useEffect, useCallback } from 'react';
import NextImage from 'next/image';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { createClient } from '@/utils/supabase/client';
import { User } from '@supabase/supabase-js';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import FloatingWindow from '@/components/profilepage/FloatingWindow';
import Cropper, { Area, Point } from 'react-easy-crop';

interface ProfileData {
  id: string;
  first_name: string;
  last_name: string;
  institution: string;
  region: string;
  email: string;
  profile_picture_url?: string;
}

interface ProfileCardProps {
  profile: ProfileData;
  profileId: string;
}

const supabase = createClient();

const ProfileCard: React.FC<ProfileCardProps> = ({ profile: initialProfile, profileId }) => {
  const [isEditing, setIsEditing] = useState(false);
  const [profile, setProfile] = useState(initialProfile);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [imageUrl, setImageUrl] = useState<string | null>(null);
  const [isFloatingWindowOpen, setIsFloatingWindowOpen] = useState(false);
  const [crop, setCrop] = useState<Point>({ x: 0, y: 0 });
  const [zoom, setZoom] = useState(1);
  const [croppedAreaPixels, setCroppedAreaPixels] = useState<Area | null>(null);
  const [isCropping, setIsCropping] = useState(false);
  const [tempImageFile, setTempImageFile] = useState<File | null>(null);

  useEffect(() => {
    const fetchProfilePicture = async () => {
      if (profile.profile_picture_url) {
        try {
          const { data, error } = await supabase.storage
            .from('profile-pictures')
            .createSignedUrl(profile.profile_picture_url, 60);

          if (error) {
            console.error('Error fetching profile picture:', error);
            setImageUrl(null);
          } else if (data) {
            setImageUrl(data.signedUrl);
          }
        } catch (error) {
          console.error('Error in fetchProfilePicture:', error);
          setImageUrl(null);
        }
      } else {
        setImageUrl(null);
      }
    };

    fetchProfilePicture();
  }, [profile.profile_picture_url]);

  const handleEdit = () => {
    setIsEditing(prev => !prev);
  };

  const handleSave = async () => {
    setIsSaving(true);
    setError(null);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) {
        throw new Error('User not authenticated');
      }

      const { error: updateError } = await supabase
        .from('profiles')
        .update({
          first_name: profile.first_name,
          last_name: profile.last_name,
          institution: profile.institution,
          region: profile.region,
          email: profile.email,
        })
        .eq('id', user.id);

      if (updateError) {
        throw updateError;
      }

      setIsEditing(false);
    } catch (error) {
      setError('Error saving profile: ' + (error as Error).message);
    } finally {
      setIsSaving(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setProfile(prev => ({ ...prev, [name]: value }));
  };

  const handleImageSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files.length > 0) {
      const file = event.target.files[0];
      setTempImageFile(file);
      const reader = new FileReader();
      reader.onload = () => {
        setImageUrl(reader.result as string);
        setIsCropping(true);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleCropComplete = useCallback((croppedArea: Area, croppedAreaPixels: Area) => {
    setCroppedAreaPixels(croppedAreaPixels);
  }, []);

  const createImage = (url: string): Promise<HTMLImageElement> =>
    new Promise((resolve, reject) => {
      const img = document.createElement('img');
      img.addEventListener('load', () => resolve(img));
      img.addEventListener('error', (error) => reject(error));
      img.src = url;
    });

  const getCroppedImg = async (
    imageSrc: string,
    pixelCrop: Area
  ): Promise<Blob | null> => {
    const image = await createImage(imageSrc);
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    if (!ctx) {
      return null;
    }

    canvas.width = pixelCrop.width;
    canvas.height = pixelCrop.height;

    ctx.drawImage(
      image,
      pixelCrop.x,
      pixelCrop.y,
      pixelCrop.width,
      pixelCrop.height,
      0,
      0,
      pixelCrop.width,
      pixelCrop.height
    );

    return new Promise((resolve) => {
      canvas.toBlob((blob) => {
        resolve(blob);
      }, 'image/jpeg');
    });
  };

  const handleImageUpload = async () => {
    if (!tempImageFile || !croppedAreaPixels) return;

    try {
      setError(null);
      setIsSaving(true);

      const croppedImage = await getCroppedImg(imageUrl!, croppedAreaPixels);
      if (!croppedImage) {
        throw new Error('Failed to crop image');
      }

      const fileName = `${Math.random()}.jpg`;
      const filePath = `${profileId}/${fileName}`;

      let { error: uploadError } = await supabase.storage
        .from('profile-pictures')
        .upload(filePath, croppedImage, {
          contentType: 'image/jpeg'
        });

      if (uploadError) {
        throw uploadError;
      }

      const { error: updateError } = await supabase
        .from('profiles')
        .update({ profile_picture_url: filePath })
        .eq('id', profileId);

      if (updateError) {
        throw updateError;
      }

      setProfile(prev => ({ ...prev, profile_picture_url: filePath }));
      setIsCropping(false);
      setIsFloatingWindowOpen(false);

      // Fetch and set the new image URL
      const { data, error } = await supabase.storage
        .from('profile-pictures')
        .createSignedUrl(filePath, 60);
      
      if (error) {
        throw error;
      }

      if (data) {
        setImageUrl(data.signedUrl);
      }
    } catch (error) {
      setError('Error uploading image: ' + (error as Error).message);
    } finally {
      setIsSaving(false);
      setTempImageFile(null);
    }
  };

  const handleImageDelete = async () => {
    if (!profile.profile_picture_url) return;
    try {
      setError(null);
      const { error: deleteError } = await supabase.storage
        .from('profile-pictures')
        .remove([profile.profile_picture_url]);
      if (deleteError) throw deleteError;

      const { error: updateError } = await supabase
        .from('profiles')
        .update({ profile_picture_url: null })
        .eq('id', profileId);
      if (updateError) throw updateError;

      setProfile(prev => ({ ...prev, profile_picture_url: undefined }));
      setImageUrl(null);
      setIsFloatingWindowOpen(false);
    } catch (error) {
      setError('Error deleting image: ' + (error as Error).message);
    }
  };

  return (
    <div className="flex items-start space-x-8">
      <Card className="mb-4 gradient-card w-full md:w-9/12 lg:w-7/12 profile-card-color border border-black relative shadow-[0_5px_9px_0_rgba(0,0,0,0.4)]">
        <button
          onClick={handleEdit}
          className="absolute top-2 right-2 bg-white rounded-full p-2"
          disabled={isEditing}
        >
          <NextImage
            src="/profile/edit.png"
            alt="Edit"
            width={20}
            height={20}
          />
        </button>
        <CardHeader>
          <CardTitle className="profile-card-color">
            {isEditing ? (
              <>
                <input
                  name="first_name"
                  value={profile.first_name}
                  onChange={handleChange}
                  className="bg-transparent profile-card-color focus:outline-none w-full mr-2"
                />
                <input
                  name="last_name"
                  value={profile.last_name}
                  onChange={handleChange}
                  className="bg-transparent profile-card-color focus:outline-none w-full"
                />
              </>
            ) : (
              `${profile.first_name} ${profile.last_name}`
            )}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <p className="flex items-center">
            <NextImage
              src="/profile/education.png"
              alt="Education icon"
              width={16}
              height={16}
              className="mr-2"
            />
            {isEditing ? (
              <input
                name="institution"
                value={profile.institution}
                onChange={handleChange}
                className="bg-transparent profile-card-color focus:outline-none w-full"
              />
            ) : (
              profile.institution
            )}
          </p>
          <p className="flex items-center">
            <NextImage
              src="/profile/location.png"
              alt="Location icon"
              width={16}
              height={16}
              className="mr-2"
            />
            {isEditing ? (
              <input
                name="region"
                value={profile.region}
                onChange={handleChange}
                className="bg-transparent profile-card-color focus:outline-none w-full"
              />
            ) : (
              profile.region
            )}
          </p>
          <p className="flex items-center">
            <NextImage
              src="/profile/email.png"
              alt="Email icon"
              width={16}
              height={16}
              className="mr-2"
            />
            {isEditing ? (
              <input
                name="email"
                value={profile.email}
                onChange={handleChange}
                className="bg-transparent profile-card-color focus:outline-none w-full"
              />
            ) : (
              profile.email
            )}
          </p>
          {isEditing && (
            <button
              onClick={handleSave}
              className="text-white py-2 px-4 mt-4 rounded editfs custom-gradient-btn transition-all duration-200 ease-in-out hover:scale-105 hover:shadow-xl focus:outline-none"
              disabled={isSaving}
              style={{
                background: 'linear-gradient(135deg, rgb(255, 152, 5), rgb(246, 76, 85))'
              }}
            >
              {isSaving ? 'Saving...' : 'Save'}
            </button>
          )}
        </CardContent>
      </Card>
      
      <div className="flex flex-col items-center">
        <div 
          className="w-40 h-40 rounded-full overflow-hidden border-4 border-gray-300 relative cursor-pointer"
          onClick={() => setIsFloatingWindowOpen(true)}
        >
          {imageUrl ? (
            <NextImage
              src={imageUrl}
              alt="Profile Picture"
              fill
            />
          ) : (
            <NextImage
              src="/default-avatar.png"
              alt="Default Avatar"
              fill
            />
          )}
        </div>
      </div>

      <FloatingWindow
        isOpen={isFloatingWindowOpen}
        onClose={() => {
          setIsFloatingWindowOpen(false);
          setIsCropping(false);
          setTempImageFile(null);
        }}
        title={isCropping ? "Crop Your Image" : "Profile Picture Options"}
      >
        {isCropping ? (
          <div className="space-y-4">
            <div style={{ position: 'relative', width: '100%', height: 300 }}>
              <Cropper
                image={imageUrl!}
                crop={crop}
                zoom={zoom}
                aspect={1}
                onCropChange={setCrop}
                onZoomChange={setZoom}
                onCropComplete={handleCropComplete}
              />
            </div>
            <input
              type="range"
              value={zoom}
              min={1}
              max={3}
              step={0.1}
              aria-labelledby="Zoom"
              onChange={(e) => setZoom(Number(e.target.value))}
              className="w-full"
            />
            <Button onClick={handleImageUpload} disabled={isSaving} className="w-full">
              {isSaving ? 'Uploading...' : 'Upload Cropped Image'}
            </Button>
          </div>
        ) : (
          <div className="space-y-4">
            <input
              type="file"
              accept="image/*"
              onChange={handleImageSelect}
              className="block w-full text-sm text-gray-500
                file:mr-4 file:py-2 file:px-4
                file:rounded-full file:border-0
                file:text-sm file:font-semibold
                file:bg-indigo-50 file:text-indigo-700
                hover:file:bg-indigo-100"
            />
            {profile.profile_picture_url && (
              <Button onClick={handleImageDelete} variant="destructive" className="w-full">
                Delete Current Picture
              </Button>
            )}
          </div>
        )}
      </FloatingWindow>
    </div>
  );
};

export default ProfileCard;

Analyze the above code and suggest specific ways it could be made more efficient. Rate the current code's efficiency on a 1-100 scale and re-rate it after you make a list of edits.