import axios from "axios";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { BulkUserCreattionType } from "../../type/BulkUserCreattionType";
import { Ji } from "../../type/TpType";
import { CSVParseType } from "../../type/CSVParseType";

function BulkUsers() {
  const [userData, setUserData] = useState<CSVParseType[]>([]);
  const [practical, setPractical] = useState("0");
  const navigate = useNavigate();
  const [jis, setJis] = useState([]);

  const handlePracticalChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setPractical(e.target.value);
  };

  useEffect(() => {
    axios.get("/api/ji/listall").then((res) => {
      setJis(res.data);
    });
  }, []);

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files) {
      const selectedFile = event.target.files[0];
      parseCSV(selectedFile);
    }
  };

  const parseCSV = (file: File) => {
    const reader = new FileReader();
    reader.onload = (event: ProgressEvent<FileReader>) => {
      if (event.target) {
        const text = event.target.result!.toString();
        const rows = text.split("\n").map((row) => row.split(","));
        const formattedData = rows.map((row) => ({
          name: row[0],
          email: row[1],
          password: row[2],
          instance_name: row[3],
          instance_ssh: row[4],
          instance_port: row[5],
          instance_pwd: row[6],
        }));
        setUserData(formattedData);
      }
    };
    reader.readAsText(file);
  };

  const handleSubmit = () => {
    axios
      .post("/api/users", {
        users: userData.filter((user: CSVParseType) => user.name !== ""),
        jiId: 1,
      }).then((res) => {
      if (res.status === 200) {
        alert(`Users succesfully created !\n${res}`);
      }
      if (res.status === 202) 
        alert(`Couldn't create some users`);
      if (res.status === 500)
        alert(`Couldn't create ANY users`);
    });
  };

  return (
    <div className="max-w-7xl mx-auto p-5">
      <h2 className="text-2xl font-bold mb-4">Bulk User Creation</h2>
      <input
        type="file"
        accept=".csv"
        onChange={handleFileChange}
        className="file-input file-input-bordered mb-4"
      />
      {userData.length > 0 && (
        <div className="overflow-x-auto w-full">
          <table className="table w-full">
            <thead>
              <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Password</th>
                <th>Instance name</th>
                <th>Instance ssh</th>
                <th>Instance port</th>
                <th>Instance pwd</th>
              </tr>
            </thead>
            <tbody>
              {userData.map((user: BulkUserCreattionType, index: number) => (
                <tr key={index}>
                  <td>{user.name}</td>
                  <td>{user.email}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <div>
        <label className="block text-gray-700 font-semibold mb-2">Ji:</label>
        <select
          name="practical"
          value={practical}
          onChange={handlePracticalChange}
          className="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          return <option value="0">Empty</option>;
          {jis.map((ji: Ji) => {
            return <option value={ji.id}>{ji.name}</option>;
          })}
        </select>
      </div>
      <button
        onClick={handleSubmit}
        className="btn btn-primary mt-4"
        disabled={userData.length === 0 || practical == "0"}
      >
        Create Users
      </button>
    </div>
  );
}

export default BulkUsers;
