import React, { FormEvent, useEffect, useState, MouseEvent } from "react";
import { Link } from "react-router-dom";
import { mainimgApi } from "../apis";
// import { profileUpload } from "../apis/profile.api";
import { catchErrors } from "../helpers";
import { MainimgType } from "../types";
import { picture } from "../apis/profile.api";
import { MySlide } from "./adminslide";

// export interface ImgState {
//     state: MainimgType;
// }

export default function Admin() {
  // 이미지 전체 불러오기
  const [getimgs, setGetimgs] = useState<MainimgType[]>([]);

  async function imgsData() {
    const imgs = await mainimgApi.getmainimg();
    setGetimgs(imgs);
  }
  useEffect(() => {
    imgsData();
  }, []);

  // 이미지 추가하기
  const [addimg, setAddimg] = useState<MainimgType>({
    _id: "",
    theme: "",
    city: "",
    title: "",
    pic: { originalfilename: "", newfilename: "" },
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [addSuccess, setAddSuccess] = useState(false);
  const [delSuccess, setDelSuccess] = useState(false);
  const [file, setFile] = useState<File>();

  function handleSelectChange(event: React.ChangeEvent<HTMLSelectElement>) {
    const { name, value } = event.currentTarget;
    console.log(value);
    setAddimg({ ...addimg, [name]: value });
  }
  function handleInputeChange(event: React.ChangeEvent<HTMLInputElement>) {
    const { name, value } = event.currentTarget;
    setAddimg({ ...addimg, [name]: value });
  }

  function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!(file === undefined)) {
      setFile(file);
    }
  }

  async function handleSubmit(event: FormEvent) {
    event.preventDefault();
    const formdata = new FormData();
    console.log(addimg);
    formdata.append("city", addimg.city);
    formdata.append("theme", addimg.theme);
    formdata.append("title", addimg.title);
    if (!(file === undefined)) {
      formdata.append("mainimg", file);
      console.log(formdata);
      const res = await mainimgApi.mainimg(formdata);
      console.log("확인 중 ", res);
      alert("img 추가되었습니다");
    }
  }

  // 이미지 삭제하기
  async function handleDeleteClick(event: MouseEvent<HTMLButtonElement>) {
    try {
      if (confirm("삭제하시겠습니까?") == true) {
        const picId = event.currentTarget.id;
        console.log("picId : ", picId);
        const res = await mainimgApi.delmainimg(picId);
        console.log("delete img", res);
        // setGetimgs(getimgs)
        setDelSuccess(true);
        setError("");
        alert("img 삭제되었습니다");
      } else {
        return false;
      }
    } catch (error) {
      console.log("에러발생");
      catchErrors(error, setError);
    } finally {
      setLoading(false);
    }
  }

  let limit = 15;
  const numPages = Math.ceil(getimgs.length / 15);

  // const location = useLocation() as ImgState;
  // const img = location.state;

  const slides = [];
  for (let i = 0; i < numPages; i++) {
    const k = [
      getimgs
        .slice(i * limit, i * limit + limit)
        .map((picture, index: number) => (
          <div key={index}>
            <div className={`m-1 shrink-0 bg-gray-200 rounded shadow-md `}>
              <img
                src={"http://localhost:3000/images/" + picture.pic.newfilename}
                className="w-full h-10 md:h-20 object-center"
              />
              <p className="text-center text-xs">{picture.title}</p>
            </div>
            <div className="text-end">
              <button className="border-r-2 border-r-indigo-500 text-xs">
                <Link to={`/admin/${picture._id}`} state={picture}>
                  수정
                </Link>
              </button>
              <button
                id={picture._id}
                onClick={handleDeleteClick}
                className="text-xs"
              >
                삭제
              </button>
            </div>
          </div>
        )),
    ];
    slides.push(k);
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <div className="flex flex-wrap justify-center gap-3">
          <div className="gap-3 md:flex ">
            <select
              name="city"
              id="Questions"
              className="border border-3 border-black w-20 my-5"
              defaultValue="질문종류"
              onChange={handleSelectChange}
            >
              <option value="질문종류">도시</option>
              <option value="서울">서울</option>
              <option value="부산">부산</option>
              <option value="인천">인천</option>
              <option value="대구">대구</option>
              <option value="광주">광주</option>
              <option value="대전">대전</option>
              <option value="울산">울산</option>
              <option value="세종">세종</option>
              <option value="독도">독도</option>
              <option value="제주">제주</option>
            </select>
            <select
              name="theme"
              id="Questions"
              className="border border-3 border-black w-20 my-5"
              defaultValue="질문종류"
              onChange={handleSelectChange}
            >
              <option value="질문종류">테마</option>
              <option value="사이클링">사이클링</option>
              <option value="서핑">서핑</option>
              <option value="액티비티">액티비티</option>
              <option value="캠핑">캠핑</option>
              <option value="스키">스키</option>
              <option value="보트">보트</option>
              <option value="사막">사막</option>
              <option value="골프">골프</option>
              <option value="동굴">동굴</option>
              <option value="문화재">문화재</option>
              <option value="동물원">동물원</option>
              <option value="사이클링">사이클링</option>
            </select>
            <div className="flex items-center justify-end gap-3">
              <input
                type="file"
                id="files"
                className="hidden"
                onChange={handleFileChange}
              ></input>
              <label htmlFor="files" className="border-2 m-5">
                이미지 선택
              </label>
            </div>
            <div className="flex items-center justify-end gap-3 mt-2 md:mt-0">
              <p>title :</p>
              <input
                name="title"
                className="border-2 border-sky-500"
                onChange={handleInputeChange}
              />
            </div>
          </div>
          <div className="my-5 flex items-center">
            <button className="border-2 border-gray-500 rounded ">추가</button>
          </div>
        </div>
      </form>
      <div className="flex justify-center">
        <MySlide key={Math.random()} slides={slides} />
      </div>
    </div>
  );
}
