"use client";
import {
  createUserLevel,
  editUserLevel,
  getUserLevel,
} from "@/service/master-user-level";
import { Button } from "@nextui-org/button";
import { RootRaws } from "postcss/lib/root";
import React, { useEffect, useState } from "react";

// Define the shape of the parsed data
interface CSVRow {
  id: string;
  parent: string;
  name: string;
  slug: string;
  level_number: string;
  group: string;
}

export default function MappingUserLevel() {
  const [parsedData, setParsedData] = useState<CSVRow[] | null>(null);

  // Function to parse the CSV data
  function parseCSV(csvText: string): CSVRow[] {
    const rows = csvText.split("\n");
    const headers = rows[0].split("\t"); // Assuming tab-delimited CSV
    const data: CSVRow[] = [];

    for (let i = 1; i < rows.length; i++) {
      const row = rows[i].split("\t");

      // Skip empty rows or rows that don't have the correct number of columns
      if (
        row.length === headers.length &&
        row.some((cell) => cell.trim() !== "")
      ) {
        const temp = row[0].split(";");

        if (temp[0] !== "") {
          temp[4].replace("/r", "");
          console.log("tempppp", temp);
          const rowData: CSVRow = {
            id: temp[0],
            parent: temp[1],
            name: temp[2],
            slug: temp[3],
            level_number: temp[4],
            group: temp[5].replace("\r", ""),
          };
          if (i <= 3) {
            console.log("i", rowData);
          }
          data.push(rowData);
        }
      }
    }
    return data;
  }

  // Handle the file input change event
  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = function (e) {
        const csvText = e.target?.result as string;
        const data = parseCSV(csvText);
        console.log("data", data);
        setParsedData(data);
      };
      reader.readAsText(file);
    }
  };

  const doPostData = async () => {
    if (parsedData) {
      let level1 = undefined;
      let level2 = undefined;

      for (let i = 0; i < parsedData.length; i++) {
        const temp = parsedData[i];
        if (temp.level_number === "2") {
          const request = {
            aliasName: temp.slug,
            group: temp.group,
            isActive: true,
            levelNumber: 2,
            name: temp.name,
            parentLevelId: level1,
            provinceId: 0,
          };
          const res = await createUserLevel(request);
          if (res?.error) {
            break;
          }
          level2 = res?.data?.data?.id;
        } else if (temp.level_number === "3") {
          const request = {
            aliasName: temp.slug,
            group: temp.group,
            isActive: true,
            levelNumber: 3,
            name: temp.name,
            parentLevelId: level2,
            provinceId: 0,
          };
          const res = await createUserLevel(request);
          if (res?.error) {
            break;
          }
        } else {
          const request = {
            aliasName: temp.slug,
            group: temp.group,
            isActive: true,
            levelNumber: 1,
            name: temp.name,
            parentLevelId: 0,
            provinceId: 0,
          };
          const res = await createUserLevel(request);
          if (res?.error) {
            break;
          }
          level1 = res?.data?.data?.id;
        }
      }
    }
  };

  useEffect(() => {
    initFecth();
  }, []);

  const initFecth = async () => {
    const res = await getUserLevel();
    const data = res?.data?.data;
    console.log("dataa", data);
    // for (const element of data) {
    //   if (element.aliasName === "satker") {
    //     console.log("namanya", element.id);
    //     const request = {
    //       aliasName: element.aliasName,
    //       levelNumber: 2,
    //       name: element.name,
    //       parentLevelId: 692,
    //       provinceId: 0,
    //     };
    //     console.log("reqq", request);
    //     const response = await editUserLevel(request, element.id);
    //     if (response?.error) {
    //       break;
    //     }
    //   }
    // }
  };
  return (
    <div>
      <h1>Mapping User Level</h1>
      <Button onPress={doPostData}>Run</Button>
      {/* File input */}
      <input type="file" accept=".csv" onChange={handleFileChange} />

      {/* Display parsed data */}
      {parsedData && (
        <div>
          <h2>Parsed Data:</h2>
          <pre>{JSON.stringify(parsedData, null, 2)}</pre>
        </div>
      )}
    </div>
  );
}
