'use client'

import ReportTitle from '@/components/report/ReportTitle'
import ReportProfitLossCard from '@/views/apps/report/profit-loss/ReportProfitLossCard'
import ReportProfitLossContent from '@/views/apps/report/profit-loss/ReportProfitLossContent'
import Grid from '@mui/material/Grid2'
import { CircularProgress, Box } from '@mui/material'
import { useState } from 'react'
import { useProfitLossAnalytics } from '@/services/queries/analytics'
import { formatDateDDMMYYYY } from '@/utils/transform'
import Loading from '@/components/layout/shared/Loading'

const ProfitLossPage = () => {
  const today = new Date()
  const monthAgo = new Date()
  monthAgo.setDate(today.getDate() - 30)
  const [startDate, setStartDate] = useState<Date | null>(monthAgo)
  const [endDate, setEndDate] = useState<Date | null>(today)

  // Single API call at parent level
  const {
    data: profitData,
    isLoading,
    error
  } = useProfitLossAnalytics({
    date_from: formatDateDDMMYYYY(startDate!),
    date_to: formatDateDDMMYYYY(endDate!)
  })

  // Handle loading state
  if (isLoading) {
    return <Loading />
  }

  // Handle error state
  if (error) {
    return (
      <Grid container spacing={6}>
        <Grid size={{ xs: 12 }}>
          <ReportTitle title='Laba Rugi' />
        </Grid>
        <Grid size={{ xs: 12 }}>
          <Box display='flex' justifyContent='center' alignItems='center' minHeight={400}>
            <span>Error loading data: {error.message}</span>
          </Box>
        </Grid>
      </Grid>
    )
  }

  return (
    <Grid container spacing={6}>
      <Grid size={{ xs: 12 }}>
        <ReportTitle title='Laba Rugi' />
      </Grid>
      <Grid size={{ xs: 12 }}>
        <ReportProfitLossCard profitData={profitData} />
      </Grid>
      <Grid size={{ xs: 12 }}>
        <ReportProfitLossContent
          profitData={profitData}
          startDate={startDate}
          endDate={endDate}
          onStartDateChange={setStartDate}
          onEndDateChange={setEndDate}
        />
      </Grid>
    </Grid>
  )
}

export default ProfitLossPage
