'use client';

import { useState, useCallback, useRef } from 'react';
import { Button } from '@/components/ui/Button';
import { uploadRetouchImage } from '@/lib/retouch';

interface RetouchUploadProps {
  vehicleId?: string;
  onUploadComplete?: (retouchId: string) => void;
}

export function RetouchUpload({ vehicleId, onUploadComplete }: RetouchUploadProps) {
  const [isDragging, setIsDragging] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFile = useCallback(
    async (file: File) => {
      setError(null);
      setSuccess(null);

      if (!file.type.startsWith('image/')) {
        setError('Only image files are allowed');
        return;
      }

      setUploading(true);
      try {
        const result = await uploadRetouchImage(file, vehicleId);
        setSuccess(`Retouch queued. Result ID: ${result.retouch_id}`);
        if (onUploadComplete) {
          onUploadComplete(result.retouch_id);
        }
      } catch (err: unknown) {
        const apiErr = err as { error?: { message?: string } };
        setError(apiErr?.error?.message || 'Upload failed');
      } finally {
        setUploading(false);
      }
    },
    [vehicleId, onUploadComplete]
  );

  const handleDragEnter = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
  }, []);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
  }, []);

  const handleDrop = useCallback(
    (e: React.DragEvent) => {
      e.preventDefault();
      e.stopPropagation();
      setIsDragging(false);

      const files = e.dataTransfer.files;
      if (files && files.length > 0) {
        handleFile(files[0]);
      }
    },
    [handleFile]
  );

  const handleFileSelect = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const files = e.target.files;
      if (files && files.length > 0) {
        handleFile(files[0]);
      }
    },
    [handleFile]
  );

  return (
    <div data-testid="retouch-upload" className="space-y-4">
      <div
        data-testid="retouch-dropzone"
        onDragEnter={handleDragEnter}
        onDragLeave={handleDragLeave}
        onDragOver={handleDragOver}
        onDrop={handleDrop}
        onClick={() => fileInputRef.current?.click()}
        className={`
          border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors
          ${isDragging ? 'border-primary bg-primary/5' : 'border-border hover:border-primary/50'}
        `}
      >
        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          onChange={handleFileSelect}
          className="hidden"
          data-testid="retouch-file-input"
        />
        <div className="space-y-2">
          <svg
            className="mx-auto h-12 w-12 text-text-muted"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
            />
          </svg>
          <p className="text-text font-medium">
            {isDragging ? 'Drop image here' : 'Drag and drop vehicle image here'}
          </p>
          <p className="text-sm text-text-muted">or click to browse</p>
          <p className="text-xs text-text-muted">PNG, JPEG, WebP (max 50 MB)</p>
        </div>
      </div>

      {uploading && (
        <div data-testid="retouch-uploading" className="text-center text-text-muted">
          Uploading and queuing retouch...
        </div>
      )}

      {error && (
        <div data-testid="retouch-upload-error" className="p-4 bg-error/10 text-error rounded-lg">
          {error}
        </div>
      )}

      {success && (
        <div data-testid="retouch-upload-success" className="p-4 bg-green-50 text-green-700 rounded-lg">
          {success}
        </div>
      )}
    </div>
  );
}
