"use client"
import { useGlobalContext } from '@/app/context/globalContext';
import { kelvinToFarenheit, unixToDay, unixToTime } from '@/app/utils/Misc';
import { Skeleton } from '@/components/ui/skeleton';
import React from 'react'
import { FaCalendarAlt } from "react-icons/fa";

const FiveDaysForecast = () => {
    const {dailyForecast} = useGlobalContext();
    const {city, list} = dailyForecast;
    if(!dailyForecast || !city || !list){
        return <Skeleton className='h-[12rem] w-full'/>
    }
    const processData = (
        dailyData: {
            dt:number;
            main:{temp_min: number,temp_max: number}; 
        }[]
        ) => {
        let minTemp = Number.MAX_VALUE;
        let maxTemp = Number.MIN_VALUE;

        dailyData.forEach((
            day: {
                dt: number;
                main: {temp_min: number, temp_max: number};
            }
        ) => {
            if(day.main.temp_min < minTemp){
                minTemp = day.main.temp_min;
            }
            if(day.main.temp_max > maxTemp){
                maxTemp = day.main.temp_max;
            }
        });
        return {
            day: unixToDay(dailyData[0].dt),
            minTemp: kelvinToFarenheit(minTemp),
            maxTemp: kelvinToFarenheit(maxTemp),
        }
    };
    const dailyForecasts = []
        for(let i = 0; i < 40; i += 8){
            const dailyData = list.slice(i, i+8);
            dailyForecasts.push(processData(dailyData));
        }


  return (
    <div className='flex flex-col flex-1 justify-between pt-6 px-4 pb-5 border rounded-lg dark:bg-darkGgray shadow-sm dark:shadow-none'>
        <div>
            <h2 className='flex items-center gap-2'><FaCalendarAlt/> 5 Days Forecast for {city.name}</h2>
            <div className='pt-3'>{dailyForecasts.map((day, i) => {
                return <div key={i} className='py-4 flex flex-col justify-evenly border-b-2'>
                    <p className='min-w-[3rem] pb-1'>{day.day}</p>
                    <p className='text-xs flex justify-between pb-1'>
                        <span>(Low)</span>
                        <span>(High)</span>
                    </p>
                    <div className='text-xs flex flex-1 justify-between items-center gap-4'>
                        <p>{day.minTemp.toFixed(0)}°F</p>
                        <div className='flex-1 w-full h-1 rounded-lg temp-progress'></div>
                        <p>{day.maxTemp.toFixed(0)}°F</p>
                    </div>
                </div>
            })}</div>
        </div>
    </div>
  )
}

export default FiveDaysForecast