"use client";

import React, { useEffect, useState, ChangeEvent } from "react";
import 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 { DesktopDatePicker } from "@mui/x-date-pickers/DesktopDatePicker";
import AppWidgetSummary from "./app-widget-summary";
import ChartColumnSingle from "../chart-view/chart-column-single";
import ChartColumnMultiple from "../chart-view/chart-column-multiple";
import HomeChartPie from "./home-chart-pie";
import ChartHorizontalBar from "../chart-view/chart-horizontal-bar";
import { Box } from "@mui/material";

type ProfitAnalysis = {
  customerName: string;
  profitAmount: number;
};

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

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

type InvoiceStatus = {
  label: string;
  value: number;
};

type TaskCompletionByProject = {
  projectName: string;
  tasksCompleted: number;
  completionDate: string;
};

type ProjectCompletion = {
  projectName?: string;
  completionPercentage?: number;
  daysRemaining?: number;
};

type ResponsableAgenceDashboardProps = {
  agencyId?: string;
};

export default function ResponsableAgenceDashboard({ agencyId }: ResponsableAgenceDashboardProps) {
  // States for backend data
  const [tasksByStatus, setTasksByStatus] = useState<TaskStatusCounts>({});
  const [remainingDaysPerProject, setRemainingDaysPerProject] = useState<
    RemainingProject[]
  >([]);
  const [invoiceStatuses, setInvoiceStatuses] = useState<InvoiceStatus[]>([]);
  const [taskCompletionData, setTaskCompletionData] = useState<
    TaskCompletionByProject[]
  >([]);
  const [projectCompletionData, setProjectCompletionData] = useState<
    ProjectCompletion[]
  >([]);
  const [profitAnalysisData, setProfitAnalysisData] = useState<
    ProfitAnalysis[]
  >([]);

  // States for filters
  const [searchRemainingDays, setSearchRemainingDays] = useState("");
  const [searchTaskCompletion, setSearchTaskCompletion] = useState("");
  const [searchProjectCompletion, setSearchProjectCompletion] = useState("");
  const [searchProfitAnalysis, setSearchProfitAnalysis] = useState("");
  const [selectedDate, setSelectedDate] = useState<Date | null>(new Date());

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

  const handleSearchTaskCompletionChange = (
    event: ChangeEvent<HTMLInputElement>
  ) => setSearchTaskCompletion(event.target.value);

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

  const handleSearchProfitAnalysisChange = (
    event: ChangeEvent<HTMLInputElement>
  ) => setSearchProfitAnalysis(event.target.value);

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

    if (!selectedAgencyId) {
      console.warn("No agency ID provided or found in localStorage");
      return;
    }
    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:", error);
      }
    };


    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:", error);
      }
    };


    const fetchInvoiceStatuses = async () => {
      try {

        const response = await axiosInstancee.get(
          `/api/invoice/status`
        );

        setInvoiceStatuses(
          Object.entries(response.data || {}).map(
            ([label, value]) => ({
              label,
              value: Number(value),
            })
          )
        );
      } catch (error) {
        console.error("Error fetching invoice statuses:", error);
      }
    };



    const fetchTaskCompletion = async () => {
      try {

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

        setTaskCompletionData(response.data || []);
      } catch (error) {
        console.error("Error fetching task completion data:", 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:", error);
      }
    };

    const fetchProfitAnalysis = async () => {
      try {


        const response = await axiosInstancee.get(
          `/api/projects/profit-analysis`
        );

        setProfitAnalysisData(response.data || []);
      } catch (error) {
        console.error("Error fetching profit analysis data:", error);


        try {
          const altResponse = await axiosInstancee.get(
            `/api/invoice/analytics`
          );

          setProfitAnalysisData(altResponse.data || []);
        } catch (altError) {
          console.error("Error fetching from alternative profit analysis endpoint:", altError);
        }
      }
    };


    fetchTasksByStatus();
    fetchRemainingDays();
    fetchInvoiceStatuses();
    fetchTaskCompletion();
    fetchProjectCompletion();
    fetchProfitAnalysis();

  }, [agencyId]);

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



  const filteredTaskCompletion = searchTaskCompletion
    ? taskCompletionData.filter(item =>
      item.projectName.toLowerCase().includes(searchTaskCompletion.toLowerCase())
    )
    : taskCompletionData;


  const filteredProjectCompletion = searchProjectCompletion
    ? projectCompletionData.filter(item =>
      item.projectName && item.projectName.toLowerCase().includes(searchProjectCompletion.toLowerCase())
    )
    : projectCompletionData;

  const taskCompletionSeries = [{
    name: "Tasks Completed",
    data: taskCompletionData.map(item => Math.max(item.tasksCompleted, 0.1)),
    axis: taskCompletionData.map(item => item.projectName),
    color: "rgb(0, 167, 111)",
  }];

  const projectCompletionSeries = [
    {
      name: "Days Remaining",
      data: projectCompletionData.map(item => Math.round(item.daysRemaining || 0)),
      axis: projectCompletionData.map(item => item.projectName || "Unknown"),
      color: "rgb(255, 86, 48)",
    },
    {
      name: "Completion Percentage",
      data: projectCompletionData.map(item => Math.round(item.completionPercentage || 0)),
      axis: projectCompletionData.map(item => item.projectName || "Unknown"),
      color: "rgb(0, 167, 111)",
    },
  ];

  const profitAnalysisSeries = [
    {
      name: "Profit",
      data: profitAnalysisData.map((item) => item.profitAmount),
      axis: profitAnalysisData.map((item) => item.customerName),
      color: "rgb(149, 185, 198)",
    },
  ];

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <Container maxWidth="xl">
        <Typography variant="h4" sx={{ mb: { xs: 3, md: 5 } }}>
          Responsable Agence 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 */}
        <Grid container spacing={3} sx={{ mt: 2 }}>
          <Grid xs={12} md={6}>
            <Card sx={{ height: '100%', boxShadow: 'none' }}>
              <CardHeader title="Remaining Days Per Project" />
              <CardContent>
                {/* Search Field */}
                <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 }}
                />

                {/* Column Chart (replacing Horizontal Bar Chart) */}
                {remainingDaysPerProject.length > 0 ? (
                  <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: "rgb(255, 171, 0)",
                        },
                      ]}
                      searchValue={searchRemainingDays}
                    />
                  </Box>
                ) : (
                  <Typography variant="body2" color="text.secondary">
                    No data available for the selected filters.
                  </Typography>
                )}
              </CardContent>
            </Card>
          </Grid>

          {/* Invoice Status */}
          <Grid xs={12} md={6}>
            <Card sx={{ height: '100%', boxShadow: 'none' }}>
              <CardHeader title="Invoice Status" />
              <CardContent>
                <HomeChartPie
                  chart={{
                    series: invoiceStatuses.map((status) => ({
                      label: status.label,
                      value: status.value,
                    })),
                    colors: [
                      "rgb(0, 167, 111)",
                      "rgb(255, 171, 0)",
                      "rgb(255, 86, 48)",
                      "rgb(0, 184, 217)",
                    ],
                  }}
                />
              </CardContent>

            </Card>
          </Grid>
        </Grid>

        {/* Task Completion */}
        <Grid container spacing={3}>
          <Grid xs={12} md={12}>
            <Card sx={{ boxShadow: 'none' }}>
              <CardHeader title="Tasks Completed by Project" />
              <CardContent>
                {/* Search Field */}
                <TextField
                  placeholder="Search projects..."
                  value={searchTaskCompletion}
                  onChange={handleSearchTaskCompletionChange}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <Iconify
                          icon="eva:search-fill"
                          sx={{ color: "text.disabled" }}
                        />
                      </InputAdornment>
                    ),
                  }}
                  sx={{ mb: 2 }}
                />

                {/* Chart - Use the direct series instead of filtering in the component */}
                {taskCompletionData.length > 0 ? (
                  <ChartColumnSingle
                    series={taskCompletionSeries}
                    searchValue={searchTaskCompletion}
                  />
                ) : (
                  <Typography variant="body2" color="text.secondary">
                    No data available for the selected filters.
                  </Typography>
                )}
              </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 - Use the direct series */}
                {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>

        {/* Profit Analysis */}
        <Grid container spacing={3}>
          <Grid xs={12} md={12}>
            <Card sx={{ boxShadow: 'none' }}>
              <CardHeader title="Profit Analysis by Customer" />
              <CardContent>
                {/* Date Picker */}
                <DesktopDatePicker
                  label="Date"
                  value={selectedDate}
                  minDate={new Date("2017-01-01")}
                  onChange={(newValue) => setSelectedDate(newValue)}
                  slotProps={{
                    textField: {
                      fullWidth: false,
                    },
                  }}
                />
                {/* Search Field */}
                <TextField
                  placeholder="Search companies..."
                  value={searchProfitAnalysis}
                  onChange={handleSearchProfitAnalysisChange}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <Iconify
                          icon="eva:search-fill"
                          sx={{ color: "text.disabled" }}
                        />
                      </InputAdornment>
                    ),
                  }}
                  sx={{ mt: 2, mb: 2 }}
                  fullWidth
                />
                {/* Chart */}
                {profitAnalysisSeries[0].data.length > 0 ? (
                  <ChartColumnMultiple
                    series={profitAnalysisSeries}
                    searchValue={searchProfitAnalysis}
                  />
                ) : (
                  <Typography variant="body2" color="text.secondary">
                    No data available for the selected filters.
                  </Typography>
                )}
              </CardContent>
            </Card>
          </Grid>
        </Grid>
      </Container>
    </LocalizationProvider>
  );
}
