"use client";
import { FinancialByProject, fetchFinancialSummaryByProjectV2 } from '@/app/api/financialsummary';
import { Box, Card, CardContent, CardHeader, FormControl, FormControlLabel, InputLabel, MenuItem, Select, Stack, Switch } from '@mui/material';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from "react-i18next";
import ProjectFinancialCard from '../ProjectFinancialSummary/ProjectFinancialCard';
import dayjs from 'dayjs';
import { INPUT_DATE_FORMAT } from '@/app/utils/formatUtil';
import { SumOfByClient, SumOfByTeam, sumUpByClient, sumUpByTeam } from './gptFn';
import FinancialStatusByProject from './FinnancialStatusByProject';
import { generateYearRanges } from './Util';

interface Props {
    _teamId: number,
    financialSummByProject: FinancialByProject[]
  }

type InputDate = {
  startDate: string;
  endDate: string;
  label?: string;
}

type DateParams = {
  [key: number]: InputDate;
}

const FinancialSummaryPage: React.FC<Props> = ({
    _teamId,
    financialSummByProject
}) => {
  console.log(financialSummByProject)
  const { t } = useTranslation();
  var currDate: string = useMemo(() => dayjs().format(INPUT_DATE_FORMAT), [])
  var currYear: number = useMemo(() => dayjs().get("year"), [])
  // testing date
  // currDate = "2024-10-28"
  // currYear = 2024
  const startDate = "10-01"
  const endDate = "09-30"
  const lengthOfCombo = 6
  const currFinancialYear = useMemo(() => currDate > `${currYear}-${startDate}` ? currYear + 1 : currYear, [currYear])
  const [mainData, setMainData] = useState<FinancialByProject[]>(financialSummByProject)
  const [byTeam, setByTeam] = useState<SumOfByTeam[]>(() => sumUpByTeam(mainData)) // do fetch to set
  const [byProject, setByProject] = useState<FinancialByProject[]>(financialSummByProject)
  const [byClient, setByClient] = useState<SumOfByClient[]>(() => sumUpByClient(mainData))
  const [isLoading, setIsLoading] = useState(false)
  const allTeam = useMemo(() => {
    return byTeam.reduce((acc, curr) => ({
      id: 0,
      team: "All Team", 
      totalFee: acc.totalFee + curr.totalFee,
      totalBudget: acc.totalBudget + curr.totalBudget,
      manhourExpense: acc.manhourExpense + curr.manhourExpense,
      projectExpense: acc.projectExpense + curr.projectExpense,
      invoicedAmount: acc.invoicedAmount + curr.invoicedAmount,
      uninvoicedAmount: acc.uninvoicedAmount + curr.uninvoicedAmount,
      paidAmount: acc.paidAmount + curr.paidAmount,
      activeProject: acc.activeProject + curr.activeProject
    }), {
      id: 0,
      team: "All Team",
      totalFee: 0,
      totalBudget: 0,
      manhourExpense: 0,
      projectExpense: 0,
      invoicedAmount: 0,
      uninvoicedAmount: 0,
      paidAmount: 0,
      activeProject: 0
    })
  }, [mainData])

  const [teamId, setTeamId] = useState(_teamId)
  const [isCardClickedIndex, setIsCardClickedIndex] = useState(_teamId || 0);
  const [period, setPeriod] = useState(0);
  const [isFuture, setIsFuture] = useState(false);

  const dateMap: DateParams = useMemo(() => {
    const thisYear = currDate <= `${currYear}-${endDate}` ? 
        {startDate: `${currYear-1}-${startDate}`, endDate: `${currYear}-${endDate}`} :
        {startDate: `${currYear}-${startDate}`, endDate: `${currFinancialYear}-${endDate}`}
    const map: DateParams = {
      0: {startDate: "", endDate: ""},
      1: thisYear,
      [lengthOfCombo - 1]: {startDate: "", endDate: `${currFinancialYear-(lengthOfCombo - 2)}-${endDate}`}
    }
    for (let i = 2; i < lengthOfCombo - 1; i++) {
      map[i] = {
        startDate: `${currFinancialYear-i}-${startDate}`, 
        endDate: `${currFinancialYear-(i - 1)}-${endDate}`
      }
    }
    return map
  }, [currDate, currYear, currFinancialYear, startDate, endDate, lengthOfCombo])

  const futureDateMap: DateParams = useMemo(() => {
    const futureMap: DateParams = {};
    for (let i = 0; i < lengthOfCombo; i++){
      const financialStartDate = `${currYear+i}-${startDate}`; // Assuming financial year starts on April 1
      const financialEndDate = `${currYear+i+1}-${endDate}`; // Assuming financial year ends on March 31
      futureMap[i] = { startDate: financialStartDate, endDate: financialEndDate };
    }
    return futureMap
  }, [currDate, currYear, startDate, endDate, lengthOfCombo])
  // const comboList: string[] = useMemo(() => {
  //   const list = ["All"]
  //   var lastYear = ""
  //   for (let i = 1; i < lengthOfCombo; i++) {
  //     var currYearStr = t(" (current year) ")
  //     var yearsStr = `${currFinancialYear - i} - ${currFinancialYear - i + 1}`
  //     var str = yearsStr
  //     if (i == 1) str = yearsStr + currYearStr
  //     lastYear = `${currFinancialYear - i}`
  //     list.push(str)
  //   }
  //   list[lengthOfCombo - 1] = `< ${lastYear}`
  //   return list
  // }, [])

  const comboList: InputDate[] = useMemo(() => {
    const list = [{startDate: "", endDate: "", label: "All"}];
    const curMonth = new Date().getMonth() + 1
    // for (let i = 1; i < lengthOfCombo - 1; i++) {
    //   const yearRange = `${currFinancialYear - i} - ${currFinancialYear - i + 1}`;
    //   const label = i === 1 ? `${yearRange} ${t("(current year)")}` : yearRange;
    //   list.push(label);
    // }
    // const oldestYear = currFinancialYear - (lengthOfCombo - 2);
    // list.push(`< ${oldestYear}`);

    // for (let j = 0; j < lengthOfCombo - 3; j++) {
    //   const yearRange = `${currFinancialYear + j} - ${currFinancialYear + j + 1}`;
    //   const label = yearRange;
    //   list.push(label);
    // }
    // const latestYear = currFinancialYear + (lengthOfCombo - 2);
    // list.push(`< ${latestYear}`);
    const tempList = generateYearRanges(3, curMonth)
    const combinedList = [...list, ...tempList]
    
    return combinedList;
  }, [currFinancialYear, lengthOfCombo, t]);

  const futureList: string[] = useMemo(() => {
    const result = [];

    // Get the keys of the futureDateMap
    const years = Object.keys(futureDateMap);

    // Iterate over the keys except the last one
    for (let i = 0; i < years.length - 1; i++) {
      const year = years[i];
      result.push(`${year} - ${parseInt(year) + 1}`);
    }

    // Handle the last item separately
    if (years.length > 0) {
      const lastYear = years[years.length - 1];
      result.push(`> ${lastYear}`);
    }

    return result;
  }, [futureDateMap])

  const fetchFinancialSummaryByProject = useCallback(async (endDate: string, startDate: string) => {
    setIsLoading(true)
    const data = await fetchFinancialSummaryByProjectV2(_teamId, endDate, startDate)
    setMainData(data)
    setByTeam(sumUpByTeam(data))
    setByProject(data)
    setByClient(sumUpByClient(data))
    setIsLoading(false)
  }, [setMainData, setByTeam, setByProject, setByClient, isFuture])

  const handleCardClick = useCallback((teamId: number) => {
    setIsCardClickedIndex(teamId)
    setTeamId(teamId)
  }, []);

  const handleFilter = useCallback(async (value: number) => {
    // if (isFuture){
      setPeriod(value)
      console.log(value)
      var _startDate = comboList[value].startDate
      var _endDate = comboList[value].endDate
      console.log(_startDate)
      console.log(_endDate)
    // }
    // else{
    //   setPeriod(value)
    //   console.log(value)
    //   var _startDate = futureDateMap[value as keyof DateParams].startDate
    //   var _endDate = futureDateMap[value as keyof DateParams].endDate
    //   console.log(_startDate)
    //   console.log(_endDate)
    // }
    
    await fetchFinancialSummaryByProject(_endDate, _startDate)

  }, [isCardClickedIndex, isFuture])

  useEffect(() => {
    if (teamId > 0) {
      var filterByTeam = mainData.filter(item => item.teamId == teamId)
      setByProject(filterByTeam)
      setByClient(sumUpByClient(filterByTeam))
    } else {
      setByProject(financialSummByProject)
      setByClient(sumUpByClient(mainData))
    }
  }, [teamId])
  
  return (
  <>
  <Card sx={{ display: "block" }}>
    {/* <CardHeader className="text-slate-500" title= {t("Filter")}/> */}
    <CardContent component={Stack} spacing={1}>
      <Box sx={{ minWidth: 120, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <FormControl fullWidth sx={{ mr: 2 }}>
          <InputLabel id="demo-simple-select-label">Financial Year</InputLabel>
          <Select
            labelId="demo-simple-select-label"
            id="demo-simple-select"
            value={period}
            label="Age"
            onChange={(e) => handleFilter(Number(e.target.value))}
          >
            {
              // isFuture 
              // ?
              comboList.map((item, i) => (
                <MenuItem key={i} value={i}>{item.label}</MenuItem>
              ))
              // : 
              // Object.entries(futureDateMap).map(([year, dates], index) => {
              //   const isLastItem = index === Object.keys(futureDateMap).length - 1;
              //   const str = isLastItem ? `> ${dates.startDate.slice(0,4)}` : `${dates.startDate.slice(0,4)} - ${dates.endDate.slice(0,4)}`;
              //   return <MenuItem key={year} value={year}>{str}</MenuItem>;
              // })
            }
          </Select>
        </FormControl>
        {/* <FormControlLabel
          control={
            <Switch
              checked={!isFuture}
              onChange={() => setIsFuture(!isFuture)}
              name="toggleSwitch"
              color="primary"
            />
          }
          label={isFuture ? t("Past Years") : t("Future Years")}
        /> */}
      </Box>
    </CardContent>
  </Card>
  <Card sx={{ display: "block" }}>
      <CardHeader className="text-slate-500" title= {t("Active Project Financial Status")}/>
      <CardContent component={Stack} spacing={4}>
      <div className="ml-10 mr-10" style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'start'}}>
        {_teamId == 0 && allTeam && 
          <div className="hover:cursor-pointer ml-4 mb-2 inline-block" key={0} onClick={() => handleCardClick(0)}>
            <ProjectFinancialCard 
            Title={t("All Team")}
            TeamId={0}
            TotalActiveProjectNumber={allTeam.activeProject} 
            TotalFees={allTeam.totalFee} 
            TotalBudget={allTeam.totalBudget} 
            TotalCumulative={allTeam.manhourExpense} 
            TotalProjectExpense={allTeam.projectExpense} 
            TotalInvoicedAmount={allTeam.invoicedAmount}
            TotalUnInvoicedAmount={allTeam.totalFee - allTeam.invoicedAmount} 
            // TotalUnInvoicedAmount={allTeam.uninvoicedAmount} 
            TotalReceivedAmount={allTeam.paidAmount} 
            CashFlowStatus={allTeam.invoicedAmount >= (allTeam.projectExpense + allTeam.manhourExpense) ? "Positive" : "Negative"} 
            CostPerformanceIndex={!isFinite(allTeam.invoicedAmount/(allTeam.projectExpense + allTeam.manhourExpense)) ? 0 : allTeam.invoicedAmount/(allTeam.projectExpense + allTeam.manhourExpense) || 0} 
            ProjectedCashFlowStatus={allTeam.totalFee >= (allTeam.projectExpense + allTeam.manhourExpense) ? "Positive" : "Negative"} 
            ProjectedCPI={!isFinite(allTeam.totalFee/(allTeam.projectExpense + allTeam.manhourExpense)) ? 0 : allTeam.totalFee/(allTeam.projectExpense + allTeam.manhourExpense) || 0} 
            ClickedIndex={isCardClickedIndex} 
            Index={0}/>
        </div>}
          {byTeam.length > 0 && byTeam.map((record) => (
            <div className="hover:cursor-pointer ml-4 mb-2 inline-block" key={record.id} onClick={() => handleCardClick(record.id)}>
                  <ProjectFinancialCard 
                  Title={record.team} 
                  TeamId={record.id} 
                  TotalActiveProjectNumber={record.activeProject} 
                  TotalFees={record.totalFee} 
                  TotalBudget={record.totalBudget} 
                  TotalCumulative={record.manhourExpense} 
                  TotalProjectExpense={record.projectExpense} 
                  TotalInvoicedAmount={record.invoicedAmount} 
                  TotalUnInvoicedAmount={Math.abs(record.totalFee - record.invoicedAmount)} 
                  // TotalUnInvoicedAmount={Math.abs(record.uninvoicedAmount)} 
                  TotalReceivedAmount={record.paidAmount} 
                  CashFlowStatus={record.invoicedAmount >= (record.projectExpense + record.manhourExpense) ? "Positive" : "Negative"} 
                  CostPerformanceIndex={!isFinite(record.invoicedAmount/(record.projectExpense + record.manhourExpense)) ? 0 : record.invoicedAmount/(record.projectExpense + record.manhourExpense) || 0} 
                  ProjectedCashFlowStatus={record.totalFee >= (record.projectExpense + record.manhourExpense) ? "Positive" : "Negative"} 
                  ProjectedCPI={!isFinite(record.totalFee/(record.projectExpense + record.manhourExpense)) ? 0 : record.totalFee/(record.projectExpense + record.manhourExpense) || 0} 
                  ClickedIndex={isCardClickedIndex} 
                  Index={record.id}/>
            </div>
          ))}
        </div>
      </CardContent>
  </Card> 
      <FinancialStatusByProject 
        financialSummByProject={byProject}
        financialSummByClient={byClient}
        isLoading={isLoading}
        />
  </>
  )
}
export default FinancialSummaryPage
