'use client';

import React, { useEffect, useState, ChangeEvent } from 'react';
import axiosInstance, { axiosInstancee } from '@/utils/axios';
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 TextField from '@mui/material/TextField';
import InputAdornment from '@mui/material/InputAdornment';
import Iconify from '@/shared/components/iconify';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import AppWidgetSummary from './app-widget-summary';
import ChartColumnSingle from '../chart-view/chart-column-single';
import ChartColumnMultiple from '../chart-view/chart-column-multiple';
import { Stack, useTheme, Box } from '@mui/material';
import TasksByStatus from './chart-tasks-status';

type TaskStatusCounts = {
  'in progress'?: number;
  'TO DO'?: number;
  'IN PROGRESS'?: number;
  'To Do'?: number;
  'Done'?: number;
};

type TaskStateData = {
  [projectName: string]: {
    "Done"?: number;
    "To Do"?: number;
    "in progress"?: number;
  };
};

type RemainingProject = {
  projectName: string;
  remainingDays: number;
};
type ProjectCompletion = {
  projectName?: string;
  completionPercentage?: number;
  daysRemaining?: number;
};
type DataItem = {
  date: string;
  name: string;
};

// Add props type definition
type ClientDashboardProps = {
  agencyId?: string;
};

export default function ClientDashboard({ agencyId }: ClientDashboardProps) {
  const theme = useTheme();
  // States for backend data
  const [tasksByStatus, setTasksByStatus] = useState<TaskStatusCounts>({});
  const [remainingDaysPerProject, setRemainingDaysPerProject] = useState<RemainingProject[]>([]);
  const [projectCompletionData, setProjectCompletionData] = useState<ProjectCompletion[]>([]);

  // States for filters
  const [searchRemainingDays, setSearchRemainingDays] = useState('');
  const [searchProjectCompletion, setSearchProjectCompletion] = useState('');
  const [selectedDate, setSelectedDate] = useState<Date | null>(new Date());
  const [searchValueGrp3, setSearchValueGrp3] = useState('');
  const [taskStatusData, setTaskStatusData] = useState([]);
  const [selectedDateGraphe3, setSelectedDateGraphe3] = useState<Date | null>(new Date());
  const [taskStateData, setTaskStateData] = useState<TaskStateData>({});
  const [searchValueGrp4, setSearchValueGrp4] = useState('');


  const handleSearchRemainingDaysChange = (event: ChangeEvent<HTMLInputElement>) =>
    setSearchRemainingDays(event.target.value);

  const handleSearchProjectCompletionChange = (event: ChangeEvent<HTMLInputElement>) =>
    setSearchProjectCompletion(event.target.value);

  useEffect(() => {
    const selectedAgencyId = agencyId || localStorage.getItem('selectedAgency');

    if (!selectedAgencyId) {
      console.warn("No agency ID provided or found in localStorage for client dash");
      return;
    }

    // Separate function for fetching tasks by status
    const fetchTasksByStatus = async () => {
      try {

        const response = await axiosInstancee.get(`/api/projects/tasks-by-status?agencyId=${selectedAgencyId}`);


        const normalizedTasksData: TaskStatusCounts = {};
        Object.entries(response.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);
      } catch (error) {
        console.error("Error fetching tasks by status for client dash:", error);
      }
    };

    // Separate function for fetching remaining days
    const fetchRemainingDays = async () => {
      try {

        const response = await axiosInstancee.get(`/api/projects/remaining-days?agencyId=${selectedAgencyId}`);

        setRemainingDaysPerProject(response.data || []);
      } catch (error) {
        console.error("Error fetching remaining days for client dash:", error);
      }
    };

    const fetchProjectCompletion = async () => {
      try {

        const response = await axiosInstancee.get(`/api/projects/completion?agencyId=${selectedAgencyId}`);

        setProjectCompletionData(response.data || []);
      } catch (error) {
        console.error("Error fetching project completion data for client dash:", error);
      }
    };


    const fetchTaskStateData = async () => {
      try {

        const response = await axiosInstancee.get(`/api/projects/group-by-project-and-state?agencyId=${selectedAgencyId}`);


        const responseData = response.data || {};
        const normalizedTaskStateData: TaskStateData = {};

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

        setTaskStateData(normalizedTaskStateData);
      } catch (error) {
        console.error("Error fetching task state data for client dash:", error);
      }
    };

    // Call all fetch functions independently
    fetchTasksByStatus();
    fetchRemainingDays();
    fetchProjectCompletion();
    fetchTaskStateData();

  }, [agencyId]);

  const filteredRemainingDays = remainingDaysPerProject.filter(
    (item) => item.projectName && item.projectName.toLowerCase().includes(searchRemainingDays.toLowerCase())
  );

  const filteredProjectCompletion = projectCompletionData.filter((item) =>
    item.projectName?.toLowerCase().includes(searchProjectCompletion.toLowerCase())
  );
  const filterData = (
    data: DataItem[],
    selectedDate: Date | null,
    searchValue: string
  ): DataItem[] => {
    const normalizedSearchValue = searchValue?.toLowerCase() || '';

    return data.filter((item) => {
      const matchesDate =
        !selectedDate ||
        (item.date && new Date(item.date).toDateString() === selectedDate.toDateString());

      const matchesSearch = item.name?.toLowerCase().includes(normalizedSearchValue) ?? false;

      return matchesDate && matchesSearch;
    });
  };
  const filteredTaskStatus = filterData(
    taskStatusData,
    selectedDateGraphe3,
    searchValueGrp3
  );
  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <Container maxWidth="xl">
        <Typography variant="h4" sx={{ mb: { xs: 3, md: 5 } }}>
          Client Dashboard
        </Typography>

        {/* Task Status Widgets */}
        <Grid container spacing={3}>
          <Grid xs={6} md={4}>
            <AppWidgetSummary
              title="Tasks 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="Tasks 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="Tasks Done"
              percent={(tasksByStatus['Done'] || 0) / 100}
              total={tasksByStatus['Done'] || 0}
              chart={{
                colors: ['rgb(0, 167, 111)'],
                series: Object.values(tasksByStatus || {}),
              }}
            />
          </Grid>
        </Grid>

        {/* Remaining Days Per Project and Project Completion - UNIFORMISÉS */}
        <Grid container spacing={3} sx={{ mt: 2 }}>
          <Grid xs={12} >
            <Card sx={{ height: '100%', boxShadow: 'none' }}>
              <CardHeader title="Remaining Days Per Project" />
              <CardContent>
                <TextField
                  placeholder="Search projects..."
                  value={searchRemainingDays}
                  onChange={handleSearchRemainingDaysChange}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <Iconify icon="eva:search-fill" sx={{ color: 'text.disabled' }} />
                      </InputAdornment>
                    ),
                  }}
                  sx={{ mb: 2 }}
                />
                <Box sx={{ height: 400, overflow: 'auto' }}>
                  <ChartColumnSingle
                    series={[
                      {
                        name: 'Remaining Days',
                        data: filteredRemainingDays.map((item) => item.remainingDays || 0),
                        axis: filteredRemainingDays.map((item) => item.projectName),
                        color: theme.palette.warning.main,
                      },
                    ]}
                    searchValue={searchRemainingDays}
                  />
                </Box>
              </CardContent>
            </Card>
          </Grid>

          {/* Project Completion */}
          <Grid xs={12} md={12}>
            <Card sx={{ boxShadow: 'none' }}>
              <CardHeader title="Project Completion Based on Time Remaining" />
              <CardContent>
                {/* Search Field */}
                <TextField
                  placeholder="Search projects..."
                  value={searchProjectCompletion}
                  onChange={handleSearchProjectCompletionChange}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <Iconify
                          icon="eva:search-fill"
                          sx={{ color: "text.disabled" }}
                        />
                      </InputAdornment>
                    ),
                  }}
                />

                {/* Conditional Rendering for Chart */}
                {projectCompletionData && projectCompletionData.length > 0 ? (
                  <ChartColumnMultiple
                    series={[
                      {
                        name: "Days Remaining",
                        data: filteredProjectCompletion.map((item) => Math.round(item.daysRemaining || 0)),
                        axis: filteredProjectCompletion.map((item) => item.projectName || "Unknown"),
                        color: "rgb(255, 86, 48)",
                      },
                      {
                        name: "Completion Percentage",
                        data: filteredProjectCompletion.map((item) => Math.round(item.completionPercentage || 0)),
                        axis: filteredProjectCompletion.map((item) => item.projectName || "Unknown"),
                        color: "rgb(0, 167, 111)",
                      },
                    ]}
                    searchValue={searchProjectCompletion}
                  />
                ) : (
                  <Typography variant="body2" color="text.secondary">
                    No data available for Project Completion.
                  </Typography>
                )}
              </CardContent>
            </Card>
          </Grid>
        </Grid>

        {/* Tasks by State in Each Project */}
        <Grid container spacing={3} sx={{ mt: 2 }}>
          <Grid xs={12}>
            <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column', boxShadow: 'none' }}>
              <CardHeader title="Tasks by State in Each Project" />
              <CardContent sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column' }}>
                {/* Search Field */}
                <TextField
                  placeholder="Search projects..."
                  value={searchValueGrp3}
                  onChange={(e: ChangeEvent<HTMLInputElement>) => setSearchValueGrp3(e.target.value)}
                  fullWidth
                  margin="normal"
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <Iconify icon="eva:search-fill" sx={{ color: 'text.disabled' }} />
                      </InputAdornment>
                    ),
                  }}
                  sx={{ mb: 2 }}
                />

                {/* Chart */}

                <TasksByStatus
                  title="Task States"
                  chart={{
                    colors: ['rgb(0, 167, 111)', 'rgb(255, 86, 48)', 'rgb(255, 171, 0)'],
                    series: [
                      {
                        name: 'Done',
                        data: Object.entries(taskStateData)
                          .filter(([projectName]) =>
                            projectName.toLowerCase().includes(searchValueGrp3.toLowerCase())
                          )
                          .map(([, states]) => states['Done'] || 0),
                      },
                      {
                        name: 'To Do',
                        data: Object.entries(taskStateData)
                          .filter(([projectName]) =>
                            projectName.toLowerCase().includes(searchValueGrp3.toLowerCase())
                          )
                          .map(([, states]) => states['To Do'] || 0),
                      },
                      {
                        name: 'In Progress',
                        data: Object.entries(taskStateData)
                          .filter(([projectName]) =>
                            projectName.toLowerCase().includes(searchValueGrp3.toLowerCase())
                          )
                          .map(([, states]) => states['in progress'] || 0),
                      },
                    ],
                    axis: Object.entries(taskStateData)
                      .filter(([projectName]) =>
                        projectName.toLowerCase().includes(searchValueGrp3.toLowerCase())
                      )
                      .map(([projectName]) => projectName),
                  }}
                  searchValue={searchValueGrp3}
                />

              </CardContent>
            </Card>
          </Grid>
        </Grid>
      </Container>
    </LocalizationProvider>
  );
}
