"use client";
import { FinancialByProject, fetchFinancialSummaryByProjectV2 } from '@/app/api/financialsummary';
import { Box, Card, CardContent, CardHeader, FormControl, InputLabel, MenuItem, Select, Stack } 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';

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

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

  type DateParams = {
    0: InputDate;
    2: InputDate;
    3: InputDate;
    4: InputDate;
    5: InputDate;
  }
const FinancialSummaryPage: React.FC<Props> = ({
    _teamId,
    financialSummByProject
}) => {
  console.log(financialSummByProject)
  const { t } = useTranslation();
  const curr = useMemo(() => dayjs().format(INPUT_DATE_FORMAT), [])
  const currYear = useMemo(() => dayjs().get("year"), [])
  const startDate = "10-01"
  const endDate = "09-30"
  const currFinancialYear = useMemo(() => curr > `${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(()=> {
    var _allTeam: SumOfByTeam = {
      id: 0,
      team: "All Team",
      totalFee: 0,
      totalBudget: 0,
      manhourExpense: 0,
      projectExpense: 0,
      invoicedAmount: 0,
      paidAmount: 0,
      activeProject: 0,
    }
    for (let i = 0; i < byTeam.length; i++) {
      var curr = byTeam[i]
      _allTeam["totalFee"] += curr.totalFee
      _allTeam["totalBudget"] += curr.totalBudget
      _allTeam["manhourExpense"] += curr.manhourExpense
      _allTeam["projectExpense"] += curr.projectExpense
      _allTeam["invoicedAmount"] += curr.invoicedAmount
      _allTeam["paidAmount"] += curr.paidAmount
      _allTeam["activeProject"] += curr.activeProject
    }
    return _allTeam
  }, [mainData])
  console.log(allTeam)

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

  const dateMap: DateParams = useMemo(() => ({
    0: {startDate: "", endDate: ""},
    2: {startDate: `${currFinancialYear-2}-${startDate}`, endDate: `${currFinancialYear-1}-${endDate}`},
    3: {startDate: `${currFinancialYear-3}-${startDate}`, endDate: `${currFinancialYear-2}-${endDate}`},
    4: {startDate: `${currFinancialYear-4}-${startDate}`, endDate: `${currFinancialYear-3}-${endDate}`},
    5: {startDate: "", endDate: `${currFinancialYear-4}-${endDate}`},
  }), [currYear, startDate, endDate])

  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])

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

  const handleFilter = useCallback((value: number) => {
    setPeriod(value)
    console.log(value)
    var _startDate: string = ""
    var _endDate = ""
    if (value == 1) {
      if (curr <= `${currYear}-${endDate}`) {
        _startDate = `${currYear - 1}-${startDate}`
        _endDate = `${currYear}-${endDate}`          
      } else {
        _startDate = `${currYear}-${startDate}`
        _endDate = `${currFinancialYear}-${endDate}`
      }
    } else {
      _startDate = dateMap[value as keyof DateParams].startDate
      _endDate = dateMap[value as keyof DateParams].endDate
    }
    console.log(_startDate)
    console.log(_endDate)
    fetchFinancialSummaryByProject(_endDate, _startDate)
    
  }, [isCardClickedIndex])

  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 }}>
        <FormControl fullWidth>
          <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))}
          >
            {Array.from({ length: 6 }).map((_, i) => {
                  if (i == 0) {
                    return <MenuItem key={i} value={i}>{`All`}</MenuItem>
                  } else if (i == 1) {
                    return <MenuItem key={i} value={i}>{`${currFinancialYear - i} - ${currFinancialYear - i + 1} (current year)`}</MenuItem>
                  } else if (i == 5) {
                    return <MenuItem value={i}>{`< ${currYear - i + 1}`}</MenuItem>
                  } else {
                    return <MenuItem key={i} value={i}>{`${currFinancialYear - i} - ${currFinancialYear - i + 1}`}</MenuItem>
                  }
                }
              )}
          </Select>
        </FormControl>
      </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 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 + allTeam.projectExpense} 
            TotalProjectExpense={allTeam.projectExpense} 
            TotalInvoicedAmount={allTeam.invoicedAmount} 
            TotalUnInvoicedAmount={allTeam.totalFee - allTeam.invoicedAmount} 
            TotalReceivedAmount={allTeam.paidAmount} 
            CashFlowStatus={allTeam.invoicedAmount >= (allTeam.projectExpense + allTeam.manhourExpense) ? "Positive" : "Negative"} 
            CostPerformanceIndex={allTeam.invoicedAmount/(allTeam.projectExpense + allTeam.manhourExpense) || 0} 
            ProjectedCashFlowStatus={allTeam.totalFee >= (allTeam.projectExpense + allTeam.manhourExpense) ? "Positive" : "Negative"} 
            ProjectedCPI={allTeam.totalFee/(allTeam.projectExpense + allTeam.manhourExpense)} 
            ClickedIndex={isCardClickedIndex} 
            Index={0}/>
        </div>}
          {byTeam.length > 0 && byTeam.map((record) => (
            <div className="hover:cursor-pointer ml-4 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.projectExpense + record.manhourExpense} 
                  TotalProjectExpense={record.projectExpense} 
                  TotalInvoicedAmount={record.invoicedAmount} 
                  TotalUnInvoicedAmount={Math.abs(record.totalFee - record.invoicedAmount)} 
                  TotalReceivedAmount={record.paidAmount} 
                  CashFlowStatus={record.invoicedAmount >= (record.projectExpense + record.manhourExpense) ? "Positive" : "Negative"} 
                  CostPerformanceIndex={record.invoicedAmount/(record.projectExpense + record.manhourExpense) || 0} 
                  ProjectedCashFlowStatus={record.totalFee >= (record.projectExpense + record.manhourExpense) ? "Positive" : "Negative"} 
                  ProjectedCPI={record.totalFee/(record.projectExpense + record.manhourExpense)} 
                  ClickedIndex={isCardClickedIndex} 
                  Index={record.id}/>
            </div>
          ))}
        </div>
      </CardContent>
  </Card> 
      <FinancialStatusByProject 
        financialSummByProject={byProject}
        financialSummByClient={byClient}
        isLoading={isLoading}
        />
  </>
  )
}
export default FinancialSummaryPage
