import React, { FormEvent, useState } 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,
        pic: { originalfilename: "", newfilename: "" },
    });


    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) {
            // try {
            setError("");
            console.log("user data", imgdata);
            // if (infoFormMatch(imgdata) === true) {
            // setLoading(true);
            // const res = await mainimgApi.updating(imgdata);
            // console.log("clear", res);
            // navigate("/admin", { replace: true });
            // setSuccess(true);
            // setError("");
            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 {
                console.log("ㅇ에러")
                formdata.append("updatemainimg","");
                console.log("formdata",formdata);
                const res = await mainimgApi.updateimg(formdata,imgdata._id);
                navigate("/admin", { replace: true });
                console.log("확인 중 ", res);
            }
            // }
            // } catch (error) {
            //     console.log("에러발생");
            //     catchErrors(error, setError);
            // } finally {
            //     setLoading(false);
            // }
        } else {
            return false;
        }
    }
    // console.log(user._id)
    function infoFormMatch(pic: MainimgType) {
        if (!isLength(pic.title ?? "", { min: 1 })) {
            setError("제목을 입력해 주세요.");
            return false;
        } else if (!isLength(pic.pic.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>
            <form onSubmit={reWriteSubmit} className="px-10 md:px-40">
                <table className="w-full ">
                    <thead></thead>
                    <tbody className=" border-separate border border-slate-400 ">
                        <tr >
                            <td className="border border-slate-300 min-w-max">
                                도시이름
                            </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">
                                테마이름
                            </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>
                            <td className="border border-slate-300">
                                url
                            </td>
                            <td>
                                <input
                                    type="file"
                                    id="files"
                                    className="hidden"
                                    onChange={onUploadFile}
                                ></input>
                                <label htmlFor="files" className="border-2 m-5" >
                                    이미지 선택
                                </label>
                                {imageSrc ? (
                                    <img
                                        src={imageSrc}
                                        className="object-cover object-center h-full"
                                    />
                                ) : (
                                    <img
                                        src={"http://localhost:3000/images/" + img.pic.newfilename}
                                        className="object-cover object-center h-full"
                                    />
                                )}
                            </td>
                        </tr>
                        <tr>
                            <td className="border border-slate-300">
                                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-end">
                    <button type="submit" className="border-2">
                        수정
                    </button>
                    <button className="border-2">
                        <Link to={`/admin`}>
                            취소
                        </Link>
                    </button>
                </div>
            </form>
            <Outlet />
        </div>
    );
};
