import { Container, KeenIcon, DefaultTooltip } from '@/components';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { DateRange } from 'react-day-picker';
import { useState, useEffect, useCallback } from 'react';
import { Card, Chart, YearPicker } from './blocks';
import moment from 'moment';
import { useFetchCardData, useFetchChartData } from './hooks';
import { Button } from '@/components/ui/button';
import { useFetchYear } from './hooks/useFetchYear';
import { get5LastYear } from '@/utils/Date';
import { staticChartData } from './staticChart';
import { Helmet } from 'react-helmet';

// sum -> nominal, count-> total
type CountType = 'sum' | 'count';
type ChartType = 'line' | 'bar';
type ChartLegend = 'true' | 'false';

const DashboardHomePage = () => {
  const selectYear = get5LastYear();
  const [initialYear, setInitialYear] = useState<string>('');
  const [selectedYear, setSelectedYear] = useState<string>('');
  const [count, setCount] = useState<CountType>('sum');
  const [chartType, setChartType] = useState<ChartType>('line');
  const [chartLegend, setChartLegend] = useState<ChartLegend>('true');
  const [dateRange, setDateRange] = useState<{ from: Date; to: Date }>({
    from: new Date(),
    to: new Date()
  });

  // Menyusun tanggal awal dan akhir berdasarkan selectedYear
  useEffect(() => {
    if (selectYear.length > 0 && !selectedYear) {
      let latestYear = Math.max(...selectYear.map((item) => parseInt(item, 10))).toString();
      console.log('latestYear :', latestYear);
      setSelectedYear(latestYear);
      setInitialYear(latestYear);
    }
  }, [selectYear, selectedYear]);

  useEffect(() => {
    if (selectedYear) {
      setDateRange({
        from: moment(`${selectedYear}-01-01`, 'YYYY-MM-DD').toDate(),
        to: moment(`${selectedYear}-12-31`, 'YYYY-MM-DD').toDate()
      });
    }
  }, [selectedYear]);

  useEffect(() => {
    if (initialYear) {
      setDateRange({
        from: moment(`${initialYear}-01-01`, 'YYYY-MM-DD').toDate(),
        to: moment(`${initialYear}-12-31`, 'YYYY-MM-DD').toDate()
      });
    }
  }, [initialYear]);

  const handleYearChange = (year: string) => {
    setSelectedYear(year);
  };

  const handleCountType = (value: CountType) => {
    setCount(value);
  };

  const handleChartType = (value: ChartType) => {
    setChartType(value);
  };

  const handleChartLegend = (value: ChartLegend) => {
    setChartLegend(value);
  };

  // const handleFilter = useCallback(
  //   (date: DateRange | undefined) => {
  //     setDateRange({
  //       from: date?.from ?? moment(`${selectedYear}-01-01`, 'YYYY-MM-DD').toDate(),
  //       to: date?.to ?? moment(`${selectedYear}-12-31`, 'YYYY-MM-DD').toDate()
  //     });
  //   },
  //   [selectedYear]
  // );

  const resetFilter = useCallback(() => {
    setDateRange({
      from: moment(`${initialYear}-01-01`, 'YYYY-MM-DD').toDate(),
      to: moment(`${initialYear}-12-31`, 'YYYY-MM-DD').toDate()
    });
    setSelectedYear(initialYear);
    setCount('sum');
    setChartType('line');
    setChartLegend('true');
  }, [initialYear]);

  const { cardData } = useFetchCardData(
    moment(dateRange.from).format('YYYY-MM-DD'),
    moment(dateRange.to).format('YYYY-MM-DD'),
    count
  );

  const { chartData } = useFetchChartData(
    moment(dateRange.from).format('YYYY-MM-DD'),
    moment(dateRange.to).format('YYYY-MM-DD'),
    count
  );

  const toolbar = (
    <div className="flex gap-3 items-center w-1/2">
      <div className="w-auto min-w-[120px]">
        <Select value={chartType} onValueChange={handleChartType}>
          <SelectTrigger size="sm">
            <SelectValue placeholder="Select Chart Type" />
          </SelectTrigger>
          <SelectContent className="w-32">
            <SelectItem value="line">Line</SelectItem>
            <SelectItem value="bar">Bar</SelectItem>
          </SelectContent>
        </Select>
      </div>
      <div className="w-auto min-w-[120px]">
        <Select value={chartLegend} onValueChange={handleChartLegend}>
          <SelectTrigger size="sm">
            <SelectValue placeholder="Select Legend Visibility" />
          </SelectTrigger>
          <SelectContent className="w-full">
            <SelectItem value="true">Show Legend</SelectItem>
            <SelectItem value="false">Hide Legend</SelectItem>
          </SelectContent>
        </Select>
      </div>
    </div>
  );

  return (
    <>
      <Helmet>
        <title>TPAY | Dashboard</title>
      </Helmet>
      <Container>
        <div className="flex gap-3 items-center mb-6">
          <YearPicker selectedYear={selectedYear} setSelectedYear={handleYearChange} />
          <div className="w-auto min-w-[120px]">
            <Select value={count} onValueChange={handleCountType}>
              <SelectTrigger size="sm">
                <SelectValue placeholder="Select Count Type" />
              </SelectTrigger>
              <SelectContent className="w-32">
                <SelectItem value="sum">Nominal</SelectItem>
                <SelectItem value="count">Status</SelectItem>
              </SelectContent>
            </Select>
          </div>
          {/* <DefaultTooltip title="Filter" placement="top">
          <Button variant="outline" className="h-7.5" onClick={() => handleFilter(dateRange)}>
            <KeenIcon icon="filter" />
          </Button>
        </DefaultTooltip> */}
          <DefaultTooltip title="Reset Filter" placement="top">
            <Button variant="outline" className="h-7.5" onClick={resetFilter}>
              <KeenIcon icon="arrow-circle-left" />
            </Button>
          </DefaultTooltip>
        </div>

        {/* Cards */}
        <div className="grid gap-5 lg:gap-7.5 mb-5">
          <div className="grid lg:grid-cols-4 gap-y-5 lg:gap-5 items-stretch">
            {cardData.map((data: any) => (
              <div className="lg:col-span-1" key={data.type}>
                <Card
                  title={data.type.toUpperCase()}
                  total={data.total}
                  type={data.type}
                  count={count}
                />
              </div>
            ))}
          </div>
        </div>

        {/* Chart */}
        <div className="grid gap-5 lg:gap-7.5">
          <div className="grid lg:grid-cols-1 gap-y-5 lg:gap-5 items-stretch">
            <div className="lg:col-span-1">
              <Chart
                title="Overview"
                count={12}
                toolbar={toolbar}
                chartData={staticChartData.series.map((data: any) => data.data)}
                chartType={chartType}
                chartLegend={chartLegend}
              />
            </div>
          </div>
        </div>
      </Container>
    </>
  );
};

export default DashboardHomePage;
