import { useRef, useState } from 'react';
import { ImagePlus, Loader2 } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { uploadFile, fileDownloadUrl } from '@/business/files/api';
import { getErrorMessage } from '@/shared/errors/errorMessages';
import { cn } from '@/lib/utils';

interface ImageUploadProps {
  readonly value: string | null;
  readonly onChange: (privateUrl: string | null) => void;
  /** Upload target (e.g. table "schools", field "logo"). */
  readonly table: string;
  readonly field: string;
  readonly label?: string;
  readonly shape?: 'square' | 'circle';
}

/** Reusable logo/avatar uploader: pick → upload → report the stored URL. */
export function ImageUpload({
  value,
  onChange,
  table,
  field,
  label = 'Image',
  shape = 'square',
}: ImageUploadProps) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSelect(file: File | undefined) {
    if (!file) return;
    setError(null);
    setUploading(true);
    try {
      const privateUrl = await uploadFile(table, field, file);
      onChange(privateUrl);
    } catch (err) {
      setError(getErrorMessage(err, 'Upload failed'));
    } finally {
      setUploading(false);
    }
  }

  return (
    <div className="space-y-1.5">
      <Label>{label}</Label>
      <div className="flex items-center gap-3">
        <div
          className={cn(
            'flex h-16 w-16 items-center justify-center overflow-hidden border border-slate-700/50 bg-slate-800/40 text-slate-500',
            shape === 'circle' ? 'rounded-full' : 'rounded-xl',
          )}
        >
          {value ? (
            <img src={fileDownloadUrl(value)} alt={label} className="h-full w-full object-cover" />
          ) : (
            <ImagePlus size={20} />
          )}
        </div>
        <div className="flex items-center gap-2">
          <input
            ref={inputRef}
            type="file"
            accept="image/*"
            className="hidden"
            onChange={(event) => handleSelect(event.target.files?.[0])}
          />
          <Button
            type="button"
            variant="ghost"
            disabled={uploading}
            onClick={() => inputRef.current?.click()}
            className="h-auto px-3 py-1.5 text-xs"
          >
            {uploading && <Loader2 size={14} className="mr-1.5 animate-spin" />}
            {value ? 'Replace' : 'Upload'}
          </Button>
          {value && (
            <Button
              type="button"
              variant="ghost"
              onClick={() => onChange(null)}
              className="h-auto px-2 py-1.5 text-xs text-red-400"
            >
              Remove
            </Button>
          )}
        </div>
      </div>
      {error && <p className="text-xs text-red-400">{error}</p>}
    </div>
  );
}
