'use client';

import React, { useEffect, useState, ChangeEvent } from 'react';
import Container from '@mui/material/Container';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Unstable_Grid2';
import Card from '@mui/material/Card';
import CardHeader from '@mui/material/CardHeader';
import CardContent from '@mui/material/CardContent';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import AppWidgetSummary from './app-widget-summary';
import ChartLine from '../chart-view/chart-line';
import ChartColumnSingle from '../chart-view/chart-column-single';
import TasksByStatus from './chart-tasks-status';
import { useTheme } from '@mui/material/styles';
import axios from 'axios';
import TextField from '@mui/material/TextField';
import InputAdornment from '@mui/material/InputAdornment';
import Iconify from '@/shared/components/iconify';
import axiosInstancee from '@/utils/axios';
import Box from '@mui/material/Box';

type TaskStatusCounts = {
  "in progress"?: number;
  "To Do"?: number;
  "Done"?: number;
};

type RemainingProject = {
  projectName: string;
  remainingDays: number;
};


type EmployeeDashboardProps = {
  agencyId?: string;
};

export default function EmployeeDashboard({ agencyId }: EmployeeDashboardProps) {
  const theme = useTheme();

  // States for fetched data
  const [tasksByStatus, setTasksByStatus] = useState<TaskStatusCounts>({});
  const [taskCompletionTrends, setTaskCompletionTrends] = useState<Record<string, number>>({});
  const [remainingDaysPerProject, setRemainingDaysPerProject] = useState<RemainingProject[]>([]);
  const [taskBreakdownByState, setTaskBreakdownByState] = useState<Record<string, Record<string, number>>>({});
  const [loading, setLoading] = useState(true);

  // Search state for filtering data
  const [searchValue, setSearchValue] = useState<string>('');

  const handleSearchChange = (event: ChangeEvent<HTMLInputElement>) => {
    setSearchValue(event.target.value);
  };

  useEffect(() => {
    // Fetch data from APIs
    const fetchData = async () => {
      setLoading(true);
      try {
        const selectedAgencyId = agencyId || localStorage.getItem('selectedAgency');

        const [
          tasksByStatusResponse,
          taskCompletionTrendsResponse,
          remainingDaysResponse,
          taskBreakdownResponse,
        ] = await Promise.all([
          axiosInstancee.get(`/api/projects/tasks-by-status?agencyId=${selectedAgencyId}`),
          axiosInstancee.get(`/api/projects/dashboard/task-completion-trends?agencyId=${selectedAgencyId}`),
          axiosInstancee.get(`/api/projects/remaining-days?agencyId=${selectedAgencyId}`),
          axiosInstancee.get(`/api/projects/dashboard/task-breakdown-by-state?agencyId=${selectedAgencyId}`),
        ]);

        const normalizedTasksData: TaskStatusCounts = {};
        Object.entries(tasksByStatusResponse.data).forEach(([key, value]) => {
          if (key === "TO_DO") normalizedTasksData["To Do"] = value as number;
          else if (key === "IN PROGRESS") normalizedTasksData["in progress"] = value as number;
          else if (key === "DONE") normalizedTasksData["Done"] = value as number;
          else normalizedTasksData[key as keyof TaskStatusCounts] = value as number;
        });

        setTasksByStatus(normalizedTasksData);
        setTaskCompletionTrends(taskCompletionTrendsResponse.data);
        setRemainingDaysPerProject(remainingDaysResponse.data);
        const taskBreakdownData = taskBreakdownResponse.data || {};
        const normalizedTaskBreakdown: Record<string, Record<string, number>> = {};

        Object.entries(taskBreakdownData).forEach(([projectName, states]: [string, any]) => {
          normalizedTaskBreakdown[projectName] = {
            "Done": states["DONE"] || 0,
            "To Do": states["TO_DO"] || 0,
            "in progress": states["IN PROGRESS"] || 0
          };
        });

        setTaskBreakdownByState(normalizedTaskBreakdown);
      } catch (error) {
        console.error('Error fetching data:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [agencyId]);


  if (loading) {
    return <Typography variant="h6">Loading...</Typography>;
  }

  const axis = Object.keys(taskCompletionTrends); // Dates (X-axis)
  const data = Object.values(taskCompletionTrends)

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <Container maxWidth="xl">
        <Typography
          variant="h4"
          sx={{
            mb: { xs: 3, md: 5 },
          }}
        >
          Dashboard
        </Typography>

        {/* Widgets */}
        <Grid container spacing={3}>
          <Grid xs={6} md={4}>
            <AppWidgetSummary
              title="Task In Progress"
              percent={(tasksByStatus['in progress'] || 0) / 100}
              total={tasksByStatus['in progress'] || 0}
              chart={{
                colors: ['rgb(255, 171, 0)'],
                series: Object.values(tasksByStatus),
              }}
            />
          </Grid>
          <Grid xs={6} md={4}>
            <AppWidgetSummary
              title="Task To Do"
              percent={(tasksByStatus['To Do'] || 0) / 100}
              total={tasksByStatus['To Do'] || 0}
              chart={{
                colors: ['rgb(255, 86, 48)'],
                series: Object.values(tasksByStatus),
              }}
            />
          </Grid>
          <Grid xs={6} md={4}>
            <AppWidgetSummary
              title="Task Done"
              percent={(tasksByStatus['Done'] || 0) / 100}
              total={tasksByStatus['Done'] || 0}
              chart={{
                colors: ['rgb(0, 167, 111)'],
                series: Object.values(tasksByStatus),
              }}
            />
          </Grid>
        </Grid>

        {/* Task Completion Trends and Remaining Days */}
        <Grid container spacing={3}>
          <Grid xs={12} md={6}>
            <Card sx={{ height: '100%', boxShadow: 'none' }}>
              <CardHeader title="Tasks Completed Each Day" />
              <CardContent>
                {Object.keys(taskCompletionTrends).length > 0 ? (
                  <ChartLine
                    series={[
                      {
                        name: "Nbr. Tasks",
                        data: Object.values(taskCompletionTrends),
                        axis: Object.keys(taskCompletionTrends),
                        color: "rgb(0, 167, 111)",
                      },
                    ]}
                    height={400}
                  />
                ) : (
                  <Typography variant="body2" color="text.secondary">
                    No data available
                  </Typography>
                )}
              </CardContent>
            </Card>
          </Grid>

          {/* Remaining Days Per Project */}
          <Grid xs={12} md={6}>
            <Card sx={{ height: '100%', boxShadow: 'none' }}>
              <CardHeader
                title="Remaining Days Per Project"
                action={
                  <TextField
                    placeholder="Search projects..."
                    value={searchValue}
                    onChange={handleSearchChange}
                    size="small"
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <Iconify icon="eva:search-fill" sx={{ color: 'text.disabled' }} />
                        </InputAdornment>
                      ),
                    }}
                    sx={{ width: '180px' }}
                  />
                }
              />
              <CardContent>
                <Box sx={{ height: 400, overflow: 'auto' }}>
                  <ChartColumnSingle
                    series={[
                      {
                        name: 'Remaining Days',
                        data: remainingDaysPerProject
                          .filter((item) =>
                            item.projectName.toLowerCase().includes(searchValue.toLowerCase())
                          )
                          .map((item) => item.remainingDays || 0),
                        axis: remainingDaysPerProject
                          .filter((item) =>
                            item.projectName.toLowerCase().includes(searchValue.toLowerCase())
                          )
                          .map((item) => item.projectName),
                        color: theme.palette.warning.main,
                      },
                    ]}
                    searchValue={searchValue}
                  />
                </Box>
              </CardContent>
            </Card>
          </Grid>
        </Grid>

        {/* Task Breakdown by State */}
        <Grid container spacing={3}>
          <Grid xs={12}>
            <Card sx={{ boxShadow: 'none' }}>
              <CardHeader title="Tasks by State in Each Project" />
              <CardContent>
                <TasksByStatus
                  chart={{
                    colors: [
                      theme.palette.primary.main,
                      theme.palette.error.main,
                      theme.palette.warning.main,
                    ],
                    series: Object.entries(taskBreakdownByState).map(([projectName, states]) => ({
                      name: projectName,
                      data: Object.values(states),
                    })),
                    axis: Object.keys(taskBreakdownByState),
                  }}
                  searchValue={searchValue}
                />
              </CardContent>
            </Card>
          </Grid>
        </Grid>
      </Container>
    </LocalizationProvider>
  );
}