import { useState } from "react";
import { Avatar } from "./Avatar.tsx";

interface AvatarInputProps {
  currentAvatarUrl?: string;
  onChange: (file: File | null) => void;
}

export function AvatarInput(
  { currentAvatarUrl, onChange }: AvatarInputProps,
) {
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      // Create preview URL
      const objectUrl = URL.createObjectURL(file);
      setPreviewUrl(objectUrl);
      onChange(file);

      // Clean up previous preview URL
      return () => {
        if (previewUrl) {
          URL.revokeObjectURL(previewUrl);
        }
      };
    } else {
      setPreviewUrl(null);
      onChange(null);
    }
  };

  const displayUrl = previewUrl || currentAvatarUrl;

  return (
    <div>
      <label
        htmlFor="avatar"
        className="block text-sm font-medium text-zinc-400 mb-2"
      >
        Avatar
      </label>
      <label htmlFor="avatar" className="cursor-pointer inline-block">
        <div className="border rounded-full border-zinc-700 w-16 h-16 mb-2 relative hover:border-zinc-600 transition-colors">
          {/* Camera icon overlay */}
          <div className="absolute bottom-0 right-0 bg-zinc-700 rounded-full w-5 h-5 flex items-center justify-center z-10">
            <svg
              className="w-3 h-3 text-white"
              fill="currentColor"
              viewBox="0 0 20 20"
            >
              <path
                fillRule="evenodd"
                d="M4 5a2 2 0 00-2 2v8a2 2 0 002 2h12a2 2 0 002-2V7a2 2 0 00-2-2h-1.586a1 1 0 01-.707-.293l-1.121-1.121A2 2 0 0011.172 3H8.828a2 2 0 00-1.414.586L6.293 4.707A1 1 0 015.586 5H4zm6 9a3 3 0 100-6 3 3 0 000 6z"
                clipRule="evenodd"
              />
            </svg>
          </div>

          {/* Avatar preview */}
          <div className="w-full h-full rounded-full overflow-hidden">
            {displayUrl
              ? (
                <img
                  src={displayUrl}
                  alt="Avatar preview"
                  className="w-full h-full object-cover"
                />
              )
              : <Avatar alt="Default avatar" size="lg" />}
          </div>
        </div>
      </label>
      <input
        type="file"
        id="avatar"
        name="avatar"
        accept="image/*"
        className="hidden"
        onChange={handleFileChange}
      />
    </div>
  );
}
