import React, { useRef, useState } from 'react';
import { Camera, Trash2, Loader2 } from 'lucide-react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useContactAvatar } from '@/hooks/useContactAvatar';

interface ContactAvatarUploadProps {
  contactId: string;
  avatarUrl?: string | null;
  firstName: string;
  lastName: string;
}

export function ContactAvatarUpload({
  contactId,
  avatarUrl,
  firstName,
  lastName,
}: ContactAvatarUploadProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { uploadAvatar, deleteAvatar, isUploading, isDeleting } = useContactAvatar(contactId);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);

  const initials = `${firstName[0] ?? ''}${lastName[0] ?? ''}`.toUpperCase();

  const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // Validate file type
    if (!file.type.startsWith('image/')) {
      return;
    }

    // Validate file size (max 5MB)
    if (file.size > 5 * 1024 * 1024) {
      return;
    }

    // Show preview
    const reader = new FileReader();
    reader.onloadend = () => {
      setPreviewUrl(reader.result as string);
    };
    reader.readAsDataURL(file);

    try {
      await uploadAvatar(file);
    } finally {
      setPreviewUrl(null);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  const handleDelete = async () => {
    await deleteAvatar();
  };

  const displayUrl = previewUrl || avatarUrl;
  const isLoading = isUploading || isDeleting;

  return (
    <div className="relative group">
      <Avatar className="h-20 w-20">
        {displayUrl ? (
          <AvatarImage src={displayUrl} alt={`${firstName} ${lastName}`} />
        ) : null}
        <AvatarFallback className="text-xl bg-primary/10 text-primary">
          {isLoading ? <Loader2 className="h-6 w-6 animate-spin" /> : initials}
        </AvatarFallback>
      </Avatar>

      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            variant="secondary"
            size="icon"
            className="absolute bottom-0 right-0 h-7 w-7 rounded-full shadow-md opacity-0 group-hover:opacity-100 transition-opacity"
            disabled={isLoading}
          >
            <Camera className="h-3.5 w-3.5" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="center">
          <DropdownMenuItem onClick={() => fileInputRef.current?.click()}>
            <Camera className="h-4 w-4 mr-2" />
            {avatarUrl ? 'Change Photo' : 'Upload Photo'}
          </DropdownMenuItem>
          {avatarUrl && (
            <DropdownMenuItem
              onClick={handleDelete}
              className="text-destructive focus:text-destructive"
            >
              <Trash2 className="h-4 w-4 mr-2" />
              Remove Photo
            </DropdownMenuItem>
          )}
        </DropdownMenuContent>
      </DropdownMenu>

      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        className="hidden"
        onChange={handleFileSelect}
      />
    </div>
  );
}
