"use client";

import React, { FC, useEffect, useState } from "react";
import { ScheduleType } from "@/types/ScheduleType";
import Spinner from "@/components/Spinner";
import PageTitle from "@/components/ui/PageTitle";
import { getScheduleForDate, scheduleUserDish, updateScheduleForDate } from "@/utils/api/scheduleApi";
import { UserDishType } from "@/types/ScheduledUserDishType";
import Label from "@/components/ui/Label";
import SectionTitle from "@/components/ui/SectionTitle";
import { useFetchUsers } from "@/hooks/useFetchUsers";
import { listUserDishes } from "@/utils/api/userDishApi";
import scheduleBuilder from "@/utils/scheduleBuilder";
import transformDate from "@/utils/dateBuilder";
import { ChevronLeftIcon } from "@heroicons/react/16/solid";
import Hr from "@/components/ui/Hr"
import Button from "@/components/ui/Button"

interface Props {
    date: string;
}

const ScheduleEditForm: FC<Props> = ({ date }) => {
    const [schedule, setSchedule] = useState<ScheduleType>()
    const [userDishes, setUserDishes] = useState<UserDishType[]>([])
    const [isScheduleLoading, setIsScheduleLoading] = useState(true);
    const [areUserDishesLoading, setAreUserDishesLoading] = useState(true);
    const { users } = useFetchUsers();

    useEffect(() => {
        getScheduleForDate(date)
            .then((sched: ScheduleType) => setSchedule(sched))
            .finally(() => setIsScheduleLoading(false))
    }, [date]);


    useEffect(() => {
        listUserDishes()
            .then((user_dishes: UserDishType[]) => setUserDishes(user_dishes))
            .finally(() => setAreUserDishesLoading(false))
    }, []);

    const handleSkipDay = () => {
        updateScheduleForDate(date, true)
            .then((schedule: ScheduleType) => {
                setSchedule(schedule)
            })
    }

    const handleUnskipDay = () => {
        updateScheduleForDate(date, false)
            .then((schedule: ScheduleType) => {
                setSchedule(schedule)
            })
    }

    const handleChange = (e: React.ChangeEvent<HTMLSelectElement>, userId: number) => {
        const userDishId = parseInt(e.currentTarget.value);

        if (userDishId === 0) {
            scheduleUserDish(date, userId, null, true).then(() => window.location.reload());
            return;
        }

        scheduleUserDish(date, userId, userDishId).then(() => window.location.reload());
    }

    if (isScheduleLoading || areUserDishesLoading || !schedule) {
        return <Spinner/>
    }

    const scheduleData = scheduleBuilder(schedule, users, userDishes)

    return <div>
        <div className="flex">
            <div className="flex-none">
                <PageTitle>Edit Day</PageTitle>
            </div>
            <div className="flex-grow">
                <SectionTitle className="text-right font-size-24 capitalize font-default">{ transformDate(schedule.date) }</SectionTitle>
            </div>
        </div>

        <Hr className="mb-8" />

        {
            userDishes.length === 0 && <div className="my-2">
                <div className="text-center w-full text-xl">No dishes found assigned to this user.</div>
                <div className="text-center w-full mt-2">Go ahead and add some first, or choose to skip the day.</div>
                <div className="text-center w-full">(dishes ={`>`} edit ={`>`} add user)</div>
            </div>
        }

        { schedule.is_skipped
            ? <Label>Skipped</Label>
            : (
                <>
                    {
                        scheduleData
                            .map((scheduleData) => <div className="flex w-full py-2" key={ scheduleData.user.id }>
                                <div className="flex-none px-2 font-size-18 pt-2">{ scheduleData.user.name }</div>
                                <div className="flex-grow px-2">
                                    <select
                                        className="w-full bg-gray-500 border-2 border-secondary p-2 rounded"
                                        onChange={ (e) => handleChange(e, scheduleData.user.id) }
                                        defaultValue={ scheduleData.scheduled_user_dish?.id || 0 }
                                    >
                                        <option value="0">Skip day</option>
                                        {
                                            userDishes.map((userDish: UserDishType) => <option
                                                key={ userDish.id }
                                                value={ userDish.id }
                                            >
                                                { userDish.dish.name }
                                            </option>)
                                        }
                                    </select>
                                </div>
                            </div>)
                    }
                </>
            )
        }

        <div className="text-right w-full text-accent-yellow pr-3">Changes are saved automatically</div>

        <Hr className="mt-8" />

        <div className="pt-3 flex gap-4">
            <Button variant="secondary" appearance="outline" className="flex-grow" href="/" icon={<ChevronLeftIcon />}>
                Back to schedule
            </Button>
            <div className="flex-none w-1/3">{
                schedule.is_skipped
                    ? <Button onClick={ handleUnskipDay } variant="accent" appearance="outline" type="button">Unskip Day</Button>
                    : <Button onClick={ handleSkipDay } variant="accent" appearance="outline" type="button" className="w-full">Skip Day</Button>
            }</div>
        </div>
    </div>
}

export default ScheduleEditForm