import React, { useEffect, MouseEvent, useState, useRef } from "react";
import { Outlet, useSearchParams } from "react-router-dom";
import Theme from "./theme";
import Citylist from "../Pages/citylist";
import { getPicure } from "../Pages/pic";
import { MySlide } from "../Pages/myslide";

const initSearchParams = { theme: "", city: "" };

export default function Body() {
  let limit = 15;
  const [searchParams, setSearchParams] = useSearchParams(initSearchParams);

  let getPics = getPicure();

  useEffect(() => {
    console.log(searchParams.get("theme"), searchParams.get("city"));
    setSearchParams(searchParams);
  }, []);

  const themeHandleClick = (event: MouseEvent<HTMLButtonElement>) => {
    console.log(`theme id= ${event.currentTarget.id}`);
    setSearchParams({
      ...Object.fromEntries(searchParams),
      theme: event.currentTarget.id,
    });
    // setPage(1)
  };

  const cityHandleClick = (event: MouseEvent<HTMLButtonElement>) => {
    console.log(`city id= ${event.currentTarget.id}`);
    setSearchParams({
      ...Object.fromEntries(searchParams),
      city: event.currentTarget.id,
    });
  };

  //picture insert
  let themechange = searchParams.get("theme");
  let citylistchange = searchParams.get("city");

  const Idpics = getPics.filter((p) => {
    return (
      (p.themeid == themechange && p.cityid == citylistchange) ||
      (p.themeid == themechange && citylistchange == "") ||
      (themechange == "" && p.cityid == citylistchange) ||
      (themechange == "" && citylistchange == "")
    );
  });

  const numPages = Math.ceil(Idpics.length / 15);

  const slides = []
  for (let i = 0; i < numPages; i++) {
    const k = [
          Idpics.slice(i * limit, i * limit + limit).map((pic, index: number) => (
            <div
              className={`m-1 shrink-0 bg-gray-200 rounded shadow-md `}
              key={index}>
              <img
                src={pic.url}
                className="w-full h-10 md:h-20 object-center"
              />
              <p className="text-center text-xs">{pic.name}</p>
            </div>
          ))]
    slides.push(k);
  }

  return (
    <div className="flex flex-col">
      <Theme handleClick={themeHandleClick} />
      <div className="flex flex-col md:flex-row py-5 ">
        <div className="w-50">
          <Citylist handleClick={cityHandleClick} />
        </div>
        <div className="flex flex-col">
          <MySlide key={Math.random()}
            slides={slides}
          />
        </div>
      </div>
      <Outlet />
    </div>
    // Body Page
  );
}
