import React, { useEffect, useState, useRef } from "react";

export default function FileUpload({ onCodeParsed, reset }) {
  const [preview, setPreview] = useState(null);
  const inputRef = useRef(null); // ✅ create the ref

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    if (!file) return;

    setPreview({ name: file.name, size: file.size });

    const reader = new FileReader();

    reader.onload = () => {
      const code = reader.result;
      if (typeof onCodeParsed === "function") {
        onCodeParsed(code, file.name);
      }
    };

    reader.readAsText(file);
  };

 // ✅ Reset file input and preview when `reset` changes
  useEffect(() => {
    setPreview(null);
    if (inputRef.current) inputRef.current.value = "";
  }, [reset]);

  const triggerUpload = () => {
    if (inputRef.current) {
      inputRef.current.click(); // ✅ safe
    }
  };

  return (
    <div style={wrapperStyle}>
      <button onClick={triggerUpload} style={labelStyle}>
        📁 Upload Code
      </button>
      <input
        ref={inputRef}
        type="file"
        accept=".js,.ts,.py,.java,.cpp,.cs,.txt"
        onChange={handleFileChange}
        hidden
      />

      {preview && (
        <div style={previewStyle}>
          <strong>{preview.name}</strong> — {(preview.size / 1024).toFixed(1)} KB
        </div>
      )}
    </div>
  );
}

const wrapperStyle = {
  display: "flex",
  flexDirection: "column",
  alignItems: "flex-start",
};

const labelStyle = {
  display: "inline-block",
  padding: "8px 16px",
  backgroundColor: "#1e1e2f",
  color: "#fff",
  borderRadius: "8px",
  cursor: "pointer",
  border: "1px solid #444",
  marginBottom: "6px",
  fontSize: "0.95rem",
};

const previewStyle = {
  color: "#ccc",
  fontSize: "0.85rem",
};