import { useState } from 'react';
import { fileHandler, handleExportHandler } from './utils/option';

// Test uchun JSON ma'lumot
const jsonData = [
  { id: 1, name: "Ali", age: 25 },
  { id: 2, name: "Vali", age: 30 },
  { id: 3, name: "Hasan", age: 28 }
];

function App() {
  const [excelFile, setExcelFile] = useState(null);
  const [jsonFile, setJsonFile] = useState(null);
  const [data, setData] = useState([]);

  // excel to json
  const handleFile = async () => {
    try {
      const result = await fileHandler(excelFile);
      setData(result);
    } catch (error) {
      console.error("Error reading file:", error);
    }
  }

  // json to excel
  const handleExport = () => {
    if (jsonFile) {
      handleExportHandler(jsonFile); // sending json data
    }
  };

  // json to excel
  const handleExportWithoutFile = () => {
    handleExportHandler(jsonData); // sending json data
  };

  return (
    <>
      <div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: "12px" }}>
          <div>
            <input
              type="file"
              accept='.xls, .xlsx, .csv'
              id='upload_file'
              onClick={e => e.target.value = null}
              onChange={event => setExcelFile(event.target.files[0])}
            />
            <button type='button' onClick={handleFile}>Convert to JSON format</button>
          </div>

          <div style={{ width: "2px", height: "30px", background: "#000" }}></div>

          <div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
            <input
              type="file"
              accept='.json'
              id='upload_file'
              onClick={e => e.target.value = null}
              onChange={event => setJsonFile(event.target.files[0])}
            />
            <button onClick={handleExport}>Export to Excel with file</button>
            <button onClick={handleExportWithoutFile}>Export to Excel without file</button>
          </div>
        </div>

        <pre>
          {data}
        </pre>
      </div>
    </>
  )
}

export default App;
