import { useState, useCallback } from "react";

interface UploadPanelProps {
  onUpload: (file: File) => void;
  isAnalyzing: boolean;
  onReset: () => void;
  hasResults: boolean;
}

export default function UploadPanel({ onUpload, isAnalyzing, onReset, hasResults }: UploadPanelProps) {
  const [isDragging, setIsDragging] = useState(false);
  const [preview, setPreview] = useState<string | null>(null);
  const [fileName, setFileName] = useState("");

  const handleFile = useCallback((file: File | null) => {
    if (!file) return;

    // Validate file type
    const validTypes = ["image/jpeg", "image/png", "image/webp", "image/bmp"];
    if (!validTypes.includes(file.type)) {
      alert("Please upload a valid image file (JPEG, PNG, WebP, or BMP)");
      return;
    }

    // Create preview
    const reader = new FileReader();
    reader.onload = (e) => {
      setPreview(e.target?.result as string);
      setFileName(file.name);
    };
    reader.readAsDataURL(file);
  }, []);

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

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

  const handleDrop = useCallback(
    (e: React.DragEvent) => {
      e.preventDefault();
      setIsDragging(false);
      const file = e.dataTransfer.files[0];
      handleFile(file);
    },
    [handleFile]
  );

  const handleInputChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0] || null;
      handleFile(file);
    },
    [handleFile]
  );

  const handleAnalyze = useCallback(() => {
    if (!preview) return;

    // Convert base64 to file for upload
    fetch(preview)
      .then((res) => res.blob())
      .then((blob) => {
        const file = new File([blob], fileName, { type: blob.type });
        onUpload(file);
      });
  }, [preview, fileName, onUpload]);

  const handleClear = useCallback(() => {
    setPreview(null);
    setFileName("");
    onReset();
  }, [onReset]);

  return (
    <div className="rigo-upload-panel">
      {!preview ? (
        <label
          id="rigo-upload-zone"
          className={`rigo-upload-zone ${isDragging ? "dragging" : ""}`}
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          onDrop={handleDrop}
        >
          <input
            type="file"
            accept="image/*"
            onChange={handleInputChange}
            style={{ display: "none" }}
          />
          <div className="rigo-upload-icon">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
              <polyline points="17 8 12 3 7 8" />
              <line x1="12" y1="3" x2="12" y2="15" />
            </svg>
          </div>
          <p className="rigo-upload-text">
            <strong>Drop your EOS X-ray here</strong>
            <br />
            or click to browse
          </p>
          <p className="rigo-upload-hint">Supports JPEG, PNG, WebP, BMP</p>
        </label>
      ) : (
        <div className="rigo-upload-preview-container">
          <div className="rigo-upload-preview">
            <img src={preview} alt="X-ray preview" />
            <div className="rigo-upload-preview-overlay">
              <span style={{ color: "white", fontSize: "0.875rem" }}>{fileName}</span>
            </div>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: "12px" }}>
            <button
              className="rigo-btn rigo-btn-primary rigo-btn-block rigo-btn-lg"
              onClick={handleAnalyze}
              disabled={isAnalyzing}
            >
              {isAnalyzing ? (
                <>
                  <span className="rigo-spinner"></span>
                  Generating...
                </>
              ) : hasResults ? (
                <>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <polyline points="20 6 9 17 4 12" />
                  </svg>
                  Complete
                </>
              ) : (
                <>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
                    <polyline points="3.27 6.96 12 12.01 20.73 6.96" />
                    <line x1="12" y1="22.08" x2="12" y2="12" />
                  </svg>
                  Analyze
                </>
              )}
            </button>

            <button
              className="rigo-btn rigo-btn-secondary rigo-btn-block"
              onClick={handleClear}
              disabled={isAnalyzing}
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <line x1="18" y1="6" x2="6" y2="18" />
                <line x1="6" y1="6" x2="18" y2="18" />
              </svg>
              Clear &amp; Upload New
            </button>
          </div>
        </div>
      )}

      {/* Progress Steps */}
      <div className="rigo-progress-steps" style={{ marginTop: "32px" }}>
        <div className={`rigo-progress-step ${preview ? "completed" : "active"}`}>
          <div className="rigo-progress-step-indicator">1</div>
          <div className="rigo-progress-step-content">
            <div className="rigo-progress-step-title">Upload X-Ray</div>
            <div className="rigo-progress-step-description">EOS or standard spinal radiograph</div>
          </div>
        </div>

        <div className={`rigo-progress-step ${isAnalyzing ? "active" : hasResults ? "completed" : ""}`}>
          <div className="rigo-progress-step-indicator">2</div>
          <div className="rigo-progress-step-content">
            <div className="rigo-progress-step-title">Generate Brace</div>
            <div className="rigo-progress-step-description">3D model with corrective parameters</div>
          </div>
        </div>

        <div className={`rigo-progress-step ${hasResults ? "completed" : ""}`}>
          <div className="rigo-progress-step-indicator">3</div>
          <div className="rigo-progress-step-content">
            <div className="rigo-progress-step-title">Download STL</div>
            <div className="rigo-progress-step-description">Ready for 3D printing or editing</div>
          </div>
        </div>
      </div>
    </div>
  );
}
