import { useLocalization } from '@/utils/hooks/useLocalization'
import { Helmet } from 'react-helmet'
import { useCallback, useEffect, useState } from 'react'
import WidgetFilter from './dashboard/WidgetFilter'
import { getDashboardWidgetList } from '@/proxy/dashboard/widgets'
import dayjs from 'dayjs'
import { WidgetsData } from './dashboard/models'
import Widgets from './dashboard/Widgets'
import WidgetProgress from './dashboard/WidgetProgress'
import WidgetBarChart from './dashboard/WidgetBarChart'

const Home = () => {
  const { translate } = useLocalization()

  const [loading, setLoading] = useState(false)
  const [widgetData, setWidgetData] = useState<WidgetsData[]>()

  const [startDate, setStartDate] = useState<number>(dayjs().subtract(30, 'day').unix())
  const [endDate, setEndDate] = useState<number>(dayjs().unix())
  const startDateFormat = dayjs(startDate * 1000).format('YYYY-MM-DD')
  const endDateFormat = dayjs(endDate * 1000).format('YYYY-MM-DD')

  const [chartKey, setChartKey] = useState(0)

  const handleDateChange = ([start, end]: [Date | null, Date | null]) => {
    if (start && end) {
      setStartDate(dayjs(start).unix())
      setEndDate(dayjs(end).unix())
    }
  }

  const getPerformancePercent = () => {
    const orders = widgetData?.find((a) => a.label == 'Orders')?.datavalue ?? 0
    const shipment = widgetData?.find((a) => a.label == 'Shipment')?.datavalue ?? 0

    if (shipment > orders)
      return (orders / shipment * 100.0)
    else
      return (shipment / orders * 100.0)
  }

  const getDashboardWidgets = useCallback(async () => {
    const dashboardWidgetsRequestDto = {
      tarih1: startDateFormat,
      tarih2: endDateFormat,
    }

    setChartKey((prevKey) => prevKey + 1)

    try {
      setLoading(true)
      const response = await getDashboardWidgetList(dashboardWidgetsRequestDto)
      if (response?.data) {
        setWidgetData(
          response.data.map((a) => ({
            id: a.id,
            label: a.label,
            datavalue: a.dataValue,
            datagrowShrink: a.dataGrowShrink,
            valuePrefix: a.valuePrefix,
            date: a.date,
          })),
        )
      }
    } catch (error) {
      console.error('Dashboard widget yüklenirken hata oluştu:', error)
    } finally {
      setLoading(false)
    }
  }, [startDateFormat, endDateFormat])

  useEffect(() => {
    getDashboardWidgets()
  }, [])

  return (
    <>
      <Helmet
        titleTemplate="%s | Kurs Platform"
        title={translate('::' + 'Home')}
        defaultTitle="Kurs Platform"
      ></Helmet>

      <WidgetFilter
        onFilter={getDashboardWidgets}
        handleDateChange={handleDateChange}
        startDate={startDate}
        endDate={endDate}
      />
      <Widgets loading={loading} widgetData={widgetData} />

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 mt-4">
        <WidgetBarChart
          chartKey={`Chart-${chartKey}`}
          startDateFormat={startDateFormat}
          endDateFormat={endDateFormat}
        />
        <WidgetProgress percent={getPerformancePercent()} />
      </div>

      {/* <Button
        onClick={() => {
          // x.setConfig({
          //   component: 'RolesPermission',
          //   props: { name: 'admin' },
          // })
          // apiService.fetchData({
          //   method: 'GET',
          //   url: '/api/app/test/test',
          // })
        }}
      >
        FIRE
      </Button> */}
    </>
  )
}

export default Home
