import React, { FormEvent, useState, useEffect } from "react";
import { Link, Outlet, useNavigate, useLocation } from "react-router-dom";
import { mainimgApi } from "../apis";
import isLength from "validator/lib/isLength";
import equals from "validator/lib/equals";
import { catchErrors } from "../helpers";
import { MainimgType } from "../types";

export interface ImgState {
  state: MainimgType;
}

export default function ImgRewrite() {
  // 이미지 수정
  const [theme, setTheme] = useState<string>("질문종류");
  const [city, setCity] = useState<string>("질문종류");
  const [url, setUrl] = useState<string>("");
  const [title, setTitle] = useState<string>("");
  const navigate = useNavigate();
  const location = useLocation() as ImgState;

  const img = location.state;

  const [imgdata, setImgData] = useState<MainimgType>({
    _id: img._id,
    theme: img.theme,
    city: img.city,
    title: img.title,
    fileInfo: { originalfilename: "", newfilename: "" },
  });
  useEffect(() => {
    console.log("수정 전 : ", imgdata);
  }, []);

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);
  const [file, setFile] = useState<File>();
  const [imageSrc, setImageSrc] = useState("");

  const PictureSrc = (fileBlob: Blob) => {
    const reader = new FileReader();

    reader.readAsDataURL(fileBlob);

    reader.onload = (data) => {
      if (typeof data.target?.result === "string") {
        console.log(data.target?.result);
        setImageSrc(data.target?.result);
      }
    };
  };

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

  async function reWriteSubmit(event: FormEvent) {
    event.preventDefault();
    if (confirm("수정하시겠습니까?") == true) {
      setError("");
      console.log("user data", imgdata);
      const formdata = new FormData();
      formdata.append("id", imgdata._id);
      console.log(imgdata._id);
      formdata.append("city", imgdata.city);
      formdata.append("theme", imgdata.theme);
      formdata.append("title", imgdata.title);
      console.log(formdata);
      if (!(file === undefined)) {
        formdata.append("updatemainimg", file);
        console.log("formdata", formdata);
        const res = await mainimgApi.updateimg(formdata, imgdata._id);
        navigate("/admin", { replace: true });
        console.log("확인 중 ", res);
      } else {
        formdata.append("updatemainimg", "");
        console.log("formdata", formdata);
        const res = await mainimgApi.updateimg(formdata, imgdata._id);
        navigate("/admin", { replace: true });
        console.log("확인 중 ", res);
      }
    } else {
      return false;
    }
  }
  // console.log(user._id)
  function infoFormMatch(pic: MainimgType) {
    if (!isLength(pic.title ?? "", { min: 1 })) {
      setError("제목을 입력해 주세요.");
      return false;
    } else if (!isLength(pic.fileInfo.newfilename ?? "", { min: 1 })) {
      setError("파일을 선택해 주세요.");
      return false;
    } else if (equals(pic.city, "city")) {
      setError("도시를 선택해 주세요.");
      return false;
    } else if (equals(pic.theme, "theme")) {
      setError("테마를 선택해 주세요.");
      return false;
    } else {
      return true;
    }
  }

  const cityChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    const city = event.currentTarget.value;
    const newUser = { ...imgdata, city: city };
    console.log(event.currentTarget.value);
    setCity(event.currentTarget.value);
    setImgData(newUser);
  };

  const themeChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    const theme = event.currentTarget.value;
    const newUser = { ...imgdata, theme: theme };
    console.log(event.currentTarget.value);
    setTheme(event.currentTarget.value);
    setImgData(newUser);
  };

  const titleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const title = event.currentTarget.value;
    const newUser = { ...imgdata, title: title };
    setTitle(event.currentTarget.value);
    setImgData(newUser);
  };

  const fileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const url = event.currentTarget.value;
    const newUser = {
      ...imgdata,
      pic: { originalfilename: "", newfilename: url },
    };
    setUrl(event.currentTarget.value);
    setImgData(newUser);
  };
  return (
    <div>
      <div className="bg-white md:shadow-lg rounded py-24">
        <form onSubmit={reWriteSubmit} className="px-3 md:px-25">
          <table className="m-auto">
            <thead></thead>
            <tbody>
              <tr>
                <td className="border border-slate-300 px-5">도시이름</td>
                <td>
                  <select
                    name="city"
                    className="border border-3 border-black"
                    onChange={cityChange}
                    defaultValue={img.city}
                  >
                    <option value="city">도시</option>
                    <option value="Seoul">서울</option>
                    <option value="Busan">부산</option>
                    <option value="Incheon">인천</option>
                    <option value="Daegoo">대구</option>
                    <option value="Kwangjoo">광주</option>
                    <option value="Daejeon">대전</option>
                    <option value="Woolsan">울산</option>
                    <option value="Sejong">세종</option>
                    <option value="Dokdo">독도</option>
                    <option value="Jeju">제주</option>
                  </select>
                </td>
              </tr>
              <tr>
                <td className="border border-slate-300 min-w-max px-5">
                  테마이름
                </td>
                <td>
                  <select
                    name="theme"
                    className="border border-3 border-black"
                    onChange={themeChange}
                    defaultValue={img.theme}
                  >
                    <option value="theme">테마</option>
                    <option value="cycling">사이클링</option>
                    <option value="surfing">서핑</option>
                    <option value="activity">액티비티</option>
                    <option value="camping">캠핑</option>
                    <option value="sking">스키</option>
                    <option value="boat">보트</option>
                    <option value="desert">사막</option>
                    <option value="golf">골프</option>
                    <option value="cave">동굴</option>
                    <option value="history">문화재</option>
                    <option value="zoo">동물원</option>
                    <option value="cycling">사이클링</option>
                  </select>
                </td>
              </tr>
              <tr className="items-center border border-slate-300">
                <td className="min-w-max px-7">이미지</td>
                <td>
                  <input
                    type="file"
                    id="files"
                    className="hidden"
                    onChange={onUploadFile}
                  ></input>
                  <label htmlFor="files" className="border-2">
                    이미지 선택
                  </label>
                  {imageSrc ? (
                    <img
                      src={imageSrc}
                      className="object-cover object-center h-full"
                    />
                  ) : (
                    <img
                      src={
                        "http://localhost:3000/images/" +
                        img.fileInfo.newfilename
                      }
                      className="object-cover object-center max-w-lg max-h-36"
                    />
                  )}
                </td>
              </tr>
              <tr>
                <td className="border border-slate-300 min-w-max px-9">
                  title
                </td>
                <td>
                  <input
                    className="border-2 border-sky-500 rounded w-full"
                    onChange={titleChange}
                    defaultValue={img.title}
                  />
                </td>
              </tr>
            </tbody>
          </table>
          <div className="text-center pt-10 whitespace-nowrap">
            <button
              type="submit"
              className="border-2 sm:mr-3 md:mr-10 md:text-lg"
            >
              수정
            </button>
            <button className="border-2 sm:mr-3 md:mr-10 md:text-lg">
              <Link to={`/admin`}>취소</Link>
            </button>
          </div>
        </form>
        {/* <Outlet /> */}
      </div>
      <div className="bg-lime-100 h-12" />
    </div>
  );
}
