import { CartEvent } from '@prisma/client';
import Link from "next/link";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import axiosInstance from '../../src/axiosSecure';
import DayOfWeek from "../DayOfWeek";
import common from 'src/helpers/common';

/*
model CartEvent {
  id        Int      @id @default(autoincrement())
  startTime DateTime
  endTime   DateTime
  shiftDuration Int
  shifts    Shift[]
  dayofweek DayOfWeek
  isactive    Boolean  @default(true)
}*/
interface Location {
    id: number;
    name: string;

}
interface IProps {
    item?: CartEvent;
    locations: Location[];
    inline?: false;
}

export default function CartEventForm(props: IProps) {
    const router = useRouter();
    console.log("init CartEventForm: " + JSON.stringify(props));
    const urls = {
        apiUrl: "/api/data/cartevents/",
        indexUrl: "/cart/cartevents"
    }

    const [evt, setEvt] = useState(props.item || {
        id: router.query.id,
        startTime: "09:00",//8:00
        endTime: "19:30",//20:00
        shiftDuration: 90,//120
        dayofweek: "Monday",
    });

    //const locations = props?.locations || [];
    //get locations from api
    const [locations, setLocations] = useState(props?.locations || []);
    useEffect(() => {
        const fetchLocations = async () => {
            try {
                console.log("fetching locations");
                const { data } = await axiosInstance.get("/api/data/locations");
                setLocations(data);
                console.log(data);
            } catch (error) {
                console.error(error);
            }
        };
        if (!locations.length) {
            fetchLocations();
        }
    }, []);


    useEffect(() => {
        const fetch = async (id) => {
            try {
                console.log("fetching cart event from component " + router.query.id);
                const { data } = await axiosInstance.get(urls.apiUrl + id);
                data.startTime = common.formatTimeHHmm(data.startTime)
                data.endTime = common.formatTimeHHmm(data.endTime)
                setEvt(data);

                console.log("id:" + evt.id);
                //console.log(data);
            } catch (error) {
                console.error(error);
            }
        };

        if (!props?.item) {
            setEvt(prevEvt => ({ ...prevEvt, id: router.query.id as string }));
        }

        if (evt.id) {
            fetch(parseInt(evt.id));
        }

    }, [router.query.id]);



    const handleChange = ({ target }) => {
        console.log("CartEventForm.handleChange() " + target.name + " = " + target.value);
        if (target.type === "checkbox") {
            setEvt({ ...evt, [target.name]: target.checked });
        } else if (target.type === "number") {
            console.log("setting " + target.name + " to " + parseInt(target.value));
            setEvt({ ...evt, [target.name]: parseInt(target.value) });
        } else {
            setEvt({ ...evt, [target.name]: target.value });
        }

        console.log("CartEventForm.handleChange() " + JSON.stringify(evt));
    }


    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            const eventId = evt.id;
            delete evt.id;
            evt.startTime = common.parseTimeHHmm(evt.startTime.toString());
            evt.endTime = common.parseTimeHHmm(evt.endTime.toString());

            console.log("calling api @ " + urls.apiUrl + evt.id);
            console.log(evt);
            if (eventId) { //update
                // evt.location = {
                //     id: evt.locationId
                // };
                delete evt.locationId;
                await axiosInstance.put(urls.apiUrl + router.query.id, {
                    ...evt,
                });
                toast.success("Task Updated", {
                    position: "bottom-center",
                });
            } else {

                evt.locationId = parseInt(evt.locationId?.toString());
                await axiosInstance.post(urls.apiUrl, evt);
                toast.success("Task Saved", {
                    position: "bottom-center",
                });
            }

            // if (props.inline) {
            // } else {
            router.push(urls.indexUrl);
            // }
        } catch (error) {
            // toast.error(error.response.data.message);
            console.error(error);
        }
    };

    return (
        <div className="w-full max-w-xs mt-5 mx-auto shadow-md shadow-gray-500">
            <h3 className='p-5 pb-0 text-center text-lg '>{evt.id ? "Edit '" + evt.dayofweek + "'" : "Create"} Cart Event</h3>
            <form className="form mb-0" onSubmit={handleSubmit}>
                <label className='label' htmlFor="location">Location</label>
                {locations && (
                    <select name="locationId" id="locationId" onChange={handleChange} value={evt.locationId}>
                        {locations.map((loc: Location) => (
                            <option key={loc.id} value={loc.id} type="number">{loc.name}</option>
                        ))}
                    </select>
                )}
                <label className='label' htmlFor="dayofweek">Day of Week</label>
                <DayOfWeek onChange={handleChange} selected={evt.dayofweek} />
                <label className='label' htmlFor="startTime">Start Time</label>
                <input className="shadow border form-input" type="time" name="startTime" id="startTime" onChange={handleChange} value={evt.startTime} />
                <label className='label' htmlFor="endTime">End Time</label>
                <input className="shadow border form-input" type="time" name="endTime" id="endTime" onChange={handleChange} value={evt.endTime} />

                <label className='label' htmlFor="shiftDuration">Shift Duration</label>
                <input className="shadow border form-input" type="number" name="shiftDuration" id="shiftDuration" onChange={handleChange} value={evt.shiftDuration} />

                <label className='label' htmlFor="numberOfPublishers">Max Shifts</label>
                <input className="shadow border form-input" type="number" name="numberOfPublishers" id="numberOfPublishers" onChange={handleChange} value={evt.numberOfPublishers} />

                <div className="mb-4">
                    <div className="form-check">
                        <input className="checkbox" type="checkbox" name="isactive" id="isactive" checked={evt.isactive} onChange={handleChange} />
                        <label className='label align-text-bottom' htmlFor="isactive">Active</label>
                    </div>
                </div>
                <div className="panel-actions">
                    {!props?.inline && <Link href={urls.indexUrl} className="action-button"> Отмени </Link>}
                    {evt.id &&
                        <button className="button bg-red-500 hover:bg-red-700 focus:outline-none focus:shadow-outline" type="button" onClick={async () => {
                            await axiosInstance.delete(urls.apiUrl + router.query.id);
                            router.push(urls.indexUrl);
                        }}>
                            Изтрий
                        </button>}
                    <button className="button bg-blue-500 hover:bg-blue-700 focus:outline-none focus:shadow-outline" type="submit"> {evt.id ? "Обнови" : "Създай"}</button>
                </div>

            </form >
        </div >
    )
}
