import {
  PiCalendarDotsBold,
  PiClock,
  PiCheckCircleFill,
  PiWarningCircleFill,
  PiXCircleFill,
  PiCalendarPlusFill,
} from "react-icons/pi";
import pelindoLogo from "@/assets/logos/Logo_Baru_Pelindo_(2021).png";
import dephubLogo from "@/assets/logos/LOGO_KEMENTERIAN_PERHUBUNGAN_REPUBLIK_INDONESIA.png";
import ferinesiaLogo from "@/assets/logos/ferinesia-logo-thin.png";
import { CompanyLogo } from "@/components/CompanyLogo";
import Marquee from "react-fast-marquee";
import "dayjs/locale/id";
import bgImage from "@/assets/images/graphic-node-wrbWfkoSb5w-unsplash-compress.jpg";

import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import { useEffect, useState } from "react";
import importData from "@/data/17_10_2024_TTE_BASTIONG.json";
import importCompanyInfo from "@/data/LogoLocation.json";
import { ScheduleStatus } from "@/constants/ScheduleStatus";

dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.locale("id");

interface Schedule {
  departure_datetime: string;
  dock_name: string;
  destination: string;
  status: ScheduleStatus;
  company_code: string;
  ship_name: string;
}

export function Index() {
  const [timezone, setTimezone] = useState("N/A");
  const [clock, setClock] = useState("00:00:00");
  const [date, setDate] = useState("");
  const [currentScheduleIndex, setCurrentScheduleIndex] = useState(0);
  const [grouppedSchedules, setGrouppedSchedules] = useState<
    {
      key: string;
      items: Schedule[];
    }[][]
  >([]);
  const [companyInfo, setCompanyInfo] =
    useState<Record<string, { logo_location: string | null }>>(
      importCompanyInfo
    );

  const [data, setData] = useState<{
    harbor: {
      name: string;
      address: string;
    };
    embed_link: string[];
    marquee_text: string[];
    schedules: Schedule[];
  }>(importData);

  const chunkArray = (array: Schedule[], chunkSize: number) => {
    const result = [];
    for (let i = 0; i < array.length; i += chunkSize) {
      result.push(array.slice(i, i + chunkSize));
    }
    return result;
  };

  const groupDepartureDatetimes = (data: Schedule[], chunkSize = 5) => {
    const sortDates = data.sort(
      (x, y) =>
        dayjs(x.departure_datetime).unix() - dayjs(y.departure_datetime).unix()
    );
    const scheduleChunks = chunkArray(sortDates, chunkSize);
    const tempResult = [];

    const todayDatetime = dayjs();
    const tomorrowDatetime = dayjs().add(1, "days");

    for (const scheduleChunk of scheduleChunks) {
      const tempHolder: Record<string, Schedule[]> = {};
      for (const schedule of scheduleChunk) {
        const parseDatetime = dayjs(schedule.departure_datetime).diff(
          dayjs().startOf('day'),
          "days"
        );
        
        if (parseDatetime == 0) {
          if (
            !(
              `(Hari Ini) - ${todayDatetime.format("DD MMMM YYYY")}|1` in
              tempHolder
            )
          )
            tempHolder[
              `(Hari Ini) - ${todayDatetime.format("DD MMMM YYYY")}|1`
            ] = [];
          tempHolder[
            `(Hari Ini) - ${todayDatetime.format("DD MMMM YYYY")}|1`
          ].push(schedule);
        }

        if (parseDatetime == 1) {
          if (
            !(
              `(Besok) - ${tomorrowDatetime.format("DD MMMM YYYY")}|2` in
              tempHolder
            )
          )
            tempHolder[
              `(Besok) - ${tomorrowDatetime.format("DD MMMM YYYY")}|2`
            ] = [];
          tempHolder[
            `(Besok) - ${tomorrowDatetime.format("DD MMMM YYYY")}|2`
          ].push(schedule);
        }

        if (parseDatetime > 1) {
          if (!(`Mendatang|3` in tempHolder)) tempHolder[`Mendatang|3`] = [];
          tempHolder[`Mendatang|3`].push(schedule);
        }
      }
      tempResult.push(tempHolder);
    }

    const finaleResult = [];

    for (const groupped of tempResult) {
      const temporaryFinale = [];
      const sortItAgain = Object.keys(groupped).sort((idA, idB) =>
        (idA.split("|")[1]! as unknown as number) >
        (idB.split("|")[1]! as unknown as number)
          ? 1
          : -1
      );
      for (const key of sortItAgain) {
        temporaryFinale.push({ key: key.split("|")[0], items: groupped[key] });
      }
      finaleResult.push(temporaryFinale);
    }

    return finaleResult;
  };

  useEffect(() => {
    const currentTimezone = dayjs.tz.guess();
    switch (currentTimezone) {
      case "Asia/Jakarta": {
        setTimezone("WIB");
        break;
      }

      case "Asia/Jayapura": {
        setTimezone("WIT");
        break;
      }

      case "Asia/Pontianak":
      case "Asia/Makassar": {
        setTimezone("WITA");
        break;
      }
    }
    /**
     * Asia/Jakarta
     * Asia/Jayapura
     * Asia/Makassar
     * Asia/Pontianak
     *
     */
    setInterval(() => {
      const _clock = dayjs().format("HH:mm:ss");
      const _date = dayjs().format("DD MMM YYYY");
      setClock(_clock);
      setDate(_date);
    }, 1000);

    setGrouppedSchedules(groupDepartureDatetimes(data.schedules, 4));
  }, []);

  useEffect(() => {
    if (grouppedSchedules.length != 0) {
      setInterval(() => {
        setCurrentScheduleIndex(
          (current) => (current + 1) % grouppedSchedules.length
        );
      }, 10000);
    }
  }, [grouppedSchedules]);

  return (
    <>
      <div className="h-screen pl-4 pr-4 pt-4">
        <div className="grid grid-cols-12 items-center">
          <div className="col-span-4">
            <div className="flex items-center">
              <img src={ferinesiaLogo} className="max-h-12" />
              <h3 className="ml-2 text-6xl font-bold text-[#117AD1]">
                FERI<span className="text-[#FFCE46]">NESIA</span>
              </h3>
            </div>
          </div>
          <div className="col-span-4">
            <h3 className="text-5xl font-bold text-center text-[#2F95FA]">
              PELABUHAN BASTIONG
            </h3>
          </div>
          <div className="col-span-4">
            <h3 className="text-3xl font-bold text-right">
              {date} {clock} {timezone}
            </h3>
          </div>
        </div>
        <div className="grid grid-cols-12 gap-8 mt-8" style={{ height: "75%" }}>
          <div className="col-span-12">
            <div className="flex flex-col bg-white border shadow-sm rounded-xl p-4 md:p-5 h-full">
              <h3 className="text-4xl font-bold text-gray-800 text-center underline">
                KEBERANGKATAN
              </h3>

              <div className="mt-8">
                <table className="min-w-full max-w-full divide-y divide-gray-200 overflow-y-scroll">
                  <thead>
                    <tr>
                      <th
                        scope="col"
                        className="text-center text-4xl uppercase"
                        style={{ width: "10%", letterSpacing: "3px" }}
                      >
                        JAM
                      </th>
                      <th
                        scope="col"
                        className="text-center text-4xl font-bold uppercase w-2/5"
                        style={{letterSpacing: "3px"}}
                      >
                        KAPAL
                      </th>
                      <th
                        scope="col"
                        className="text-center text-4xl font-bold uppercase w-1/5"
                        style={{letterSpacing: "3px"}}
                      >
                        TUJUAN
                      </th>
                      <th
                        scope="col"
                        className="text-center text-4xl font-bold uppercase w-1/4"
                        style={{letterSpacing: "3px"}}
                      >
                        STATUS
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    {grouppedSchedules[currentScheduleIndex] != undefined &&
                      grouppedSchedules[currentScheduleIndex].map((x, i) => (
                        <>
                          <tr key={i}>
                            <td colSpan={4} className="text-center py-4">
                              <div className="flex gap-2 justify-center">
                                <PiCalendarDotsBold size={38} />
                                <span className="text-3xl font-bold uppercase">
                                  {x.key}
                                </span>
                              </div>
                            </td>
                          </tr>
                          {x.items.map((y, j) => (
                            <tr key={j} className="odd:bg-[#598eee] even:bg-[#dde8fc] odd:text-[#ffffff] even:text-[#0f79cf]">
                              <td className="px-4 py-2 whitespace-nowrap text-sm ">
                                <h3 className="text-4xl font-bold text-center uppercase">
                                  {x.key == "Mendatang" ? dayjs(y.departure_datetime).format("DD-MMM-YYYY") : dayjs(y.departure_datetime).format("HH:mm ") + timezone}
                                  
                                </h3>
                              </td>
                              <td className="px-4 py-2 whitespace-nowrap text-sm font-medium ">
                                <div className="flex flex-row items-center gap-4">
                                  <div>
                                    <CompanyLogo
                                      location={
                                        companyInfo[y.company_code]
                                          .logo_location
                                      }
                                      width={72}
                                    />
                                  </div>
                                  <div>
                                    <h4 className="text-4xl font-medium uppercase">
                                      {y.ship_name}
                                    </h4>
                                  </div>
                                </div>
                              </td>
                              <td className="px-4 py-2 whitespace-nowrap text-sm ">
                                <h3 className="text-4xl font-medium text-center uppercase">
                                  {y.destination}
                                </h3>
                              </td>
                              <td className="px-4 py-2 font-medium">
                                <div className="flex flex-row items-center gap-2 uppercase">
                                  {y.status == ScheduleStatus.NOT_AVAILABLE && (
                                    <>
                                      <PiXCircleFill
                                        size={50}
                                      />
                                      <h3 className="text-4xl">
                                        Belum tersedia
                                      </h3>
                                    </>
                                  )}
                                  {y.status == ScheduleStatus.SCHEDULED && (
                                    <>
                                      <PiCalendarPlusFill
                                        size={50}
                                      />
                                      <h3 className="text-4xl">Dijadwalkan</h3>
                                    </>
                                  )}
                                  {y.status == ScheduleStatus.AVAILABLE && (
                                    <>
                                      <PiCheckCircleFill
                                        size={50}
                                      />
                                      <h3 className="text-4xl">Tersedia</h3>
                                    </>
                                  )}
                                  {y.status ==
                                    ScheduleStatus.PREPARE_TO_DEPART && (
                                    <>
                                      <PiWarningCircleFill
                                        size={50}
                                      />
                                      <h3 className="text-4xl">
                                        Bersiap Berangkat
                                      </h3>
                                    </>
                                  )}
                                  {y.status == ScheduleStatus.CANCELED && (
                                    <>
                                      <PiXCircleFill
                                        size={50}
                                      />
                                      <h3 className="text-4xl">Dibatalkan</h3>
                                    </>
                                  )}
                                </div>
                              </td>
                            </tr>
                          ))}
                        </>
                      ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>

        <div className="fixed bottom-5">
          <div className="border-2 rounded-md mt-4 h-28 flex">
            <div className="bg-blue-400 h-full items-center justify-center flex w-[320px]">
              <h3 className="text-5xl text-center text-white">INFORMASI</h3>
            </div>
            <div className="whitespace-nowrap flex items-center overflow-x-hidden ml-1">
              <Marquee speed={100}>
                {data.marquee_text.map((x) => (
                  <h3 className="text-5xl ml-4 font-bold">{x}</h3>
                ))}
              </Marquee>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
