import { yupResolver } from "@hookform/resolvers/yup";
import ReassignSongModal from "Components/ReassignSongModal";
import React from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { ClipLoader } from "react-spinners";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import { getAllMixSeasonAPI } from "Src/services/mixSeasonService";
import {
  getAllProjectAPI,
  getAllUnAssignedSubSongsAPI,
  reassignSongsAPI,
  updateSubProjectDetailsAPI,
} from "Src/services/projectService";
import { replaceBrTagToNextLine, sortSeasonAsc } from "Utils/utils";
import * as yup from "yup";

const columns = [
  {
    header: "",
    accessor: "checkbox_col",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "ID",
    accessor: "id",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Producer",
    accessor: "member_name",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Mix Season",
    accessor: "mix_season",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Artist",
    accessor: "artist_name",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Song Title",
    accessor: "type_name",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Key",
    accessor: "song_key",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "BPM",
    accessor: "bpm",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Assigned",
    accessor: "program_name",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Lyrics",
    accessor: "lyrics",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Notes",
    accessor: "notes",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
];

const AdminListUnAssignedSongsPage = () => {
  const navigate = useNavigate();

  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const [showAction, setShowAction] = React.useState(false);
  const [currentTableData, setCurrentTableData] = React.useState([]);
  const [pageSize, setPageSize] = React.useState(10);
  const [pageCount, setPageCount] = React.useState(0);
  const [dataTotal, setDataTotal] = React.useState(0);
  const [currentPage, setPage] = React.useState(0);
  const [canPreviousPage, setCanPreviousPage] = React.useState(false);
  const [canNextPage, setCanNextPage] = React.useState(false);
  const [loading, setLoading] = React.useState(false);

  const [mixSeasons, setMixSeasons] = React.useState([]);
  const [filteredData, setFilteredData] = React.useState([]);
  const [canEdit, setCanEdit] = React.useState(false);

  const [showReassignModal, setShowReassignModal] = React.useState(false);

  const [projects, setProjects] = React.useState([]);
  const [showFilteredLyrics, setShowFilteredLyrics] = React.useState(false);

  const [
    selectedSubProjectIdsForReassign,
    setSelectedSubProjectIdsForReassign,
  ] = React.useState([]);

  const [filters, setFilters] = React.useState({
    mix_season_id: "",
    artist_name: null,
    type_name: null,
    song_key: null,
    bpm: null,
    program_name: null,
    lyrics: null,
  });

  const schema = yup.object({
    name: yup.string(),
    status: yup.string(),
  });

  const {
    register,
    handleSubmit,
    setError,
    reset,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  async function getData(pageNum, limitNum, filter) {
    try {
      const result = await getAllUnAssignedSubSongsAPI(
        pageNum,
        limitNum,
        filter
      );
      // const { list, total, limit, num_pages, page } = result;
      const { list } = result;
      //
      setCurrentTableData(list);
      setFilteredData(list);
      setLoading(false);
      // setPageSize(limit);
      // setPageCount(num_pages);
      // setPage(page);
      // setDataTotal(total);
      // setCanPreviousPage(page > 1);
      // setCanNextPage(page + 1 <= num_pages);
    } catch (error) {
      setLoading(false);
      tokenExpireError(dispatch, error.message);
    }
  }

  const resetForm = async () => {
    setLoading(true);
    reset();
    setFilters({
      mix_season_id: null,
      artist_name: null,
      type_name: null,
      song_key: null,
      bpm: null,
      program_name: null,
      lyrics: null,
    });
    await getData(1, pageSize);
    setLoading(false);
    setShowFilteredLyrics(false);
  };

  const handleFilterData = async (e) => {
    e.preventDefault();
    let tempTableData = currentTableData;
    console.log(currentTableData);
    setLoading(true);
    if (filters.mix_season_id) {
      tempTableData = tempTableData.filter(
        (item) => Number(item.mix_season_id) === Number(filters.mix_season_id)
      );
    }

    if (filters.artist_name) {
      tempTableData = tempTableData.filter(
        (item) => item.artist_name === filters.artist_name
      );
    }

    if (filters.type_name) {
      // type_name can be partial match
      // consider lower case for comparison
      tempTableData = tempTableData.filter((item) => {
        if (item.type_name) {
          return item.type_name.toLowerCase().includes(filters.type_name);
        }
      });
    }

    if (filters.song_key) {
      // song_key can be partial match from first character
      tempTableData = tempTableData.filter((item) => {
        if (item.song_key) {
          // return item.song_key.startsWith(filters.song_key);
          return item.song_key.toLowerCase().includes(filters.song_key);
        }
      });
    }

    if (filters.bpm) {
      tempTableData = tempTableData.filter((item) => item.bpm === filters.bpm);
    }

    // lyrics filter can be partial match
    // not every row has lyrics
    if (filters.lyrics) {
      tempTableData = tempTableData.filter((item) => {
        if (item.lyrics) {
          return item.lyrics.toLowerCase().includes(filters.lyrics);
        }
      });
      setShowFilteredLyrics(true);
    } else {
      setShowFilteredLyrics(false);
    }

    setFilteredData(tempTableData);
    setLoading(false);
  };

  const getAllMixSeasons = async () => {
    try {
      const result = await getAllMixSeasonAPI();
      if (!result.error) {
        setMixSeasons(sortSeasonAsc(result.list));
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleEditClick = (e) => {
    e.preventDefault();
    setShowReassignModal(true);
  };

  const handleReassignSong = async (projectId) => {
    try {
      const result = await reassignSongsAPI({
        project_id: projectId,
        subproject_ids: selectedSubProjectIdsForReassign,
      });
      if (!result.error) {
        showToast(globalDispatch, result.message, 5000);
        setShowReassignModal(false);
        setSelectedSubProjectIdsForReassign([]);
        // setSelectedSubProjectIdsForReassign((prevSelectedIds) => []);
        setCanEdit(false);
        await getData(1, pageSize);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getAllProjects = async () => {
    try {
      const result = await getAllProjectAPI();
      if (!result.error) {
        setProjects(result.list);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleCheckBoxChange = (e) => {
    if (e.target.checked) {
      // add to array
      setSelectedSubProjectIdsForReassign((prevSelectedIds) => [
        ...prevSelectedIds,
        Number(e.target.value),
      ]);

      setCanEdit(true);
    } else {
      // remove from array
      setSelectedSubProjectIdsForReassign((prevSelectedIds) =>
        prevSelectedIds.filter(
          (item) => Number(item) !== Number(e.target.value)
        )
      );

      if (selectedSubProjectIdsForReassign.length === 1) {
        setCanEdit(false);
      }
    }
  };

  const handleReassignSongModalClose = (e) => {
    setShowReassignModal(false);
  };

  const handleUpdateSubProjectDetails = async (payload) => {
    try {
      const result = await updateSubProjectDetailsAPI(payload);
      if (!result.error) {
        showToast(globalDispatch, "Song notes updated successfully", 5000);
        await getData(1, pageSize);
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        return;
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const renderHighlightedLyrics = (lyrics, searchTerm) => {
    if (!lyrics) return null;

    // Use a regular expression to find and highlight the search term
    const regex = new RegExp(`(${searchTerm})`, "gi");
    const parts = lyrics.split(regex);

    return (
      <>
        {parts.map((part, index) =>
          regex.test(part) ? (
            <span key={index} className="font-bold text-yellow-500">
              {replaceBrTagToNextLine(part)}
            </span>
          ) : (
            <span key={index}>{replaceBrTagToNextLine(part)}</span>
          )
        )}
      </>
    );
  };

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "unassigned-songs",
      },
    });

    (async function () {
      setLoading(true);
      await getData(1, pageSize);
      await getAllProjects();
      await getAllMixSeasons();
    })();
  }, []);

  return (
    <div className="max-w-screen h-full p-4 md:p-4 lg:p-6 xl:p-8">
      <div className="shadow-default rounded border border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
        {/* Header Section */}
        <div className="flex items-center justify-between border-b border-strokedark px-4 md:px-6 2xl:px-9">
          <h4 className="my-3 text-2xl font-semibold text-white dark:text-white">
            Songs
          </h4>
          <div className="flex items-center gap-2">
            {canEdit ? (
              <button
                type="button"
                className="inline-flex h-9 items-center justify-center rounded bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
                onClick={(e) => handleEditClick(e)}
              >
                Edit
              </button>
            ) : (
              <button
                type="button"
                className="inline-flex h-9 items-center justify-center rounded bg-gray-500 px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
                disabled
              >
                Edit
              </button>
            )}
          </div>
        </div>

        {/* Search/Filter Section */}
        <div className="mb-4 border-b border-strokedark px-4 py-4 sm:px-6 2xl:px-9 dark:border-strokedark">
          <div className="">
            <form className="">
              <div className="flex flex-wrap items-center gap-3">
                {/* Artist Input */}
                <div className="flex w-full flex-col md:w-1/4">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Artist
                  </label>
                  <input
                    type="text"
                    placeholder="Artist"
                    {...register("artist")}
                    className="h-[36px] w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-3 py-2 text-sm font-medium text-white outline-none transition placeholder:font-normal placeholder:text-bodydark focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary"
                    onChange={(e) => {
                      setFilters({
                        ...filters,
                        artist_name: e.target.value,
                      });
                    }}
                  />
                </div>

                {/* Song Title Input */}
                <div className="flex w-full flex-col md:w-1/4">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Song Title
                  </label>
                  <input
                    type="text"
                    placeholder="Song Title"
                    {...register("song_title")}
                    className="h-[36px] w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-3 py-2 text-sm font-medium text-white outline-none transition placeholder:font-normal placeholder:text-bodydark focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary"
                    onChange={(e) => {
                      setFilters({
                        ...filters,
                        type_name: e.target.value,
                      });
                    }}
                  />
                </div>

                {/* Key Input */}
                <div className="flex w-full flex-col md:w-1/4">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Key
                  </label>
                  <input
                    type="text"
                    placeholder="Key"
                    {...register("song_key")}
                    className="h-[36px] w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-3 py-2 text-sm font-medium text-white outline-none transition placeholder:font-normal placeholder:text-bodydark focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary"
                    onChange={(e) => {
                      setFilters({
                        ...filters,
                        song_key: e.target.value,
                      });
                    }}
                  />
                </div>

                {/* Lyrics Input */}
                <div className="flex w-full flex-col md:w-1/4">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Lyrics
                  </label>
                  <input
                    type="text"
                    placeholder="Lyrics"
                    {...register("lyrics")}
                    className="h-[36px] w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-3 py-2 text-sm font-medium text-white outline-none transition placeholder:font-normal placeholder:text-bodydark focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary"
                    onChange={(e) => {
                      e.preventDefault();
                      if (e.target.value.length > 0) {
                        setFilters({
                          ...filters,
                          lyrics: e.target.value,
                        });
                      } else {
                        setFilters({
                          ...filters,
                          lyrics: null,
                        });
                      }
                    }}
                  />
                </div>
              </div>

              {/* Action Buttons */}
              <div className="mt-4 flex items-center gap-2">
                <button
                  onClick={handleFilterData}
                  type="submit"
                  className="inline-flex h-9 items-center justify-center rounded bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
                >
                  Search
                </button>
                <button
                  onClick={resetForm}
                  type="button"
                  className="inline-flex h-9 items-center justify-center rounded border border-strokedark bg-danger px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
                >
                  Reset
                </button>
              </div>
            </form>
          </div>
        </div>

        {/* Table Section */}
        <div className="custom-overflow min-h-[150px] overflow-x-auto">
          <table className="w-full table-auto">
            <thead className="bg-meta-4">
              <tr>
                {columns.map((column, i) => (
                  <th
                    key={i}
                    className={`whitespace-nowrap px-3 py-3 text-left text-xs font-medium capitalize tracking-wider text-bodydark1 ${
                      column.accessor === "name" ? "xl:pl-6 2xl:pl-9" : ""
                    }`}
                  >
                    {column.header}
                    {column.isSorted && (
                      <span>{column.isSortedDesc ? " ▼" : " ▲"}</span>
                    )}
                  </th>
                ))}
              </tr>
            </thead>

            {loading && (
              <tbody>
                <tr>
                  <td colSpan={columns.length} className="text-center">
                    <span className="trans relative top-[30px] m-4 animate-pulse whitespace-nowrap p-4 pb-8 text-xl font-semibold text-white ease-out">
                      <ClipLoader color="#fff" size={20} className="mr-3" />{" "}
                      Loading Songs...
                    </span>
                  </td>
                </tr>
              </tbody>
            )}

            {!loading && filteredData.length > 0 && (
              <tbody className="cursor-pointer text-white">
                {filteredData.map((row, i) => (
                  <tr
                    key={i}
                    className="border-b border-strokedark hover:bg-primary/5"
                  >
                    {columns.map((cell, index) => {
                      if (cell.accessor === "checkbox_col") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-3 py-4 xl:px-6 2xl:px-9"
                          >
                            <input
                              type="checkbox"
                              className="bg-transparent accent-transparent"
                              value={row.id}
                              onChange={handleCheckBoxChange}
                              checked={selectedSubProjectIdsForReassign.includes(
                                row.id
                              )}
                            />
                          </td>
                        );
                      }
                      if (cell.accessor === "lyrics" && showFilteredLyrics) {
                        return (
                          <td
                            key={index}
                            className="whitespace-pre-wrap px-3 py-4 text-bodydark"
                          >
                            {renderHighlightedLyrics(
                              row.lyrics,
                              filters.lyrics
                            )}
                          </td>
                        );
                      } else if (
                        cell.accessor === "lyrics" &&
                        !showFilteredLyrics
                      ) {
                        return (
                          <td
                            key={index}
                            className="whitespace-pre-wrap px-3 py-4 text-bodydark"
                          >
                            {row.lyrics
                              ? replaceBrTagToNextLine(row.lyrics).slice(0, 30)
                              : ""}
                          </td>
                        );
                      }
                      return (
                        <td
                          key={index}
                          className={`whitespace-nowrap px-3 py-4 ${
                            index === 4 ? "text-bodydark1" : "text-bodydark"
                          }`}
                        >
                          {row[cell.accessor]}
                        </td>
                      );
                    })}
                  </tr>
                ))}
              </tbody>
            )}

            {!loading && filteredData.length === 0 && (
              <tbody>
                <tr>
                  <td colSpan={columns.length} className="text-center">
                    <span className="relative top-[10px] m-4 p-4 font-semibold text-white">
                      No data found
                    </span>
                  </td>
                </tr>
              </tbody>
            )}
          </table>
        </div>
      </div>

      {showReassignModal && (
        <ReassignSongModal
          projects={projects}
          setModalClose={handleReassignSongModalClose}
          setSelectedReassignProjectId={handleReassignSong}
        />
      )}
    </div>
  );
};

export default AdminListUnAssignedSongsPage;
