"use client";

import { useState, useEffect } 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 { DatePicker } from "@mui/x-date-pickers";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
import { useSettingsContext } from "@/shared/components/settings";
import AppWidgetSummary from "./app-widget-summary";
import ChartArea from "../chart-view/chart-area";
import AggencyNoApproved from "./agency-no-approved";
import AgencyListView from "../agency/view/agency-list-view";
import { Stack } from "@mui/material";
import AppWidget from "./app-widget";
import AllUserView from "../user/view/all-user-list-view";
import axiosInstancee from "@/utils/axios";
import { useMockedUser } from "@/hooks";

type MonthlyStats = {
  activeData: { month: string; count: number }[];
  exitData: { month: string; count: number }[];
};
const monthNames = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December",
];

type MonthlyStat = {
  count: number;
  month: string;
};

export default function AdminApplicationDashboard() {
  const { user1 } = useMockedUser();
  const settings = useSettingsContext();

  const [totalUsers, setTotalUsers] = useState(0);
  const [activeAgencies, setActiveAgencies] = useState(0);

  const [selectedDateGraphe2, setSelectedDateGraphe2] = useState<Date | null>(
    new Date()
  );
  const [monthlyStats, setMonthlyStats] = useState<MonthlyStats>({
    activeData: [],
    exitData: [],
  });

  const [selectedDateGraphe1, setSelectedDateGraphe1] = useState<Date | null>(
    new Date()
  );

  const [roleCounts, setRoleCounts] = useState({
    Manager: 0,
    Client: 0,
    Collaborator: 0,
    UnattachedUser: 0,
  });

  useEffect(() => {
    axiosInstancee
      .get("/api/user/count")
      .then((response) => {
        setTotalUsers(response.data.total);
      })
      .catch((error) => {
        console.error("Error fetching total users:", error);
      });
  }, []);

  useEffect(() => {
    axiosInstancee
      .get("/api/user/active")
      .then((response) => setActiveAgencies(response.data.active))
      .catch((error) =>
        console.error("Error fetching active agencies:", error)
      );
  }, []);

  useEffect(() => {
    if (selectedDateGraphe1) {
      const year = selectedDateGraphe1.getFullYear();
      const month = selectedDateGraphe1.getMonth() + 1; 

      axiosInstancee
        .get("/api/user/stats", { params: { year, month } }) 
        .then((response) => setMonthlyStats(response.data))
        .catch((error) =>
          console.error("Error fetching monthly agency stats:", error)
        );
    }
  }, [selectedDateGraphe1]);

  useEffect(() => {
    axiosInstancee
      .get("/api/user/roles/role/counts")
      .then((response) => {
        const data = response.data;
        console.log(data);
        setRoleCounts({
          Manager: data.MANAGER || 0, 
          Client: data.CLIENT || 0,
          Collaborator: data.COLLABORATOR || 0,
          UnattachedUser:
            (data.ADMIN || 0) +
            (data.USER || 0) +
            (data.COLLABORATOR || 0),
        });
      })
      .catch((error) => {
        console.error("Error fetching role counts:", error);
      });
  }, []);
  useEffect(() => {
    if (selectedDateGraphe1) {
      const year = selectedDateGraphe1.getFullYear();
      const month = selectedDateGraphe1.getMonth() + 1; 

      axiosInstancee
        .get("/api/user/stats", { params: { year, month } }) 
        .then((response) => setMonthlyStats(response.data))
        .catch((error) =>
          console.error("Error fetching monthly agency stats:", error)
        );
    }
  }, [selectedDateGraphe1]);

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

        <Grid container spacing={3}>
          <Grid xs={6} md={6}>
            <AppWidgetSummary
            
              title="Total Users"
              total={totalUsers}
              chart={{
                colors: ["rgb(255, 171, 0)"],
                series: [5, 18, 12, 51, 68, 11, 39, 37, 27, 20],
              }}
            />
          </Grid>

          <Grid xs={6} md={6}>
            <AppWidgetSummary
              title="Active Agency"
              percent={0.1}
              total={activeAgencies}
              chart={{
                colors: ["rgb(0, 167, 111)"],
                series: [8, 9, 31, 8, 16, 37, 8, 33, 46, 31],
              }}
            />
          </Grid>

          <Grid xs={12} md={8} lg={8}>
            <Card sx={{ height: "100%",boxShadow: 'none' }}>
              <CardHeader title="Agency Account Statistic" />
              <div
                style={{
                  width: "150px",
                  justifyContent: "center",
                  maxWidth: "100%",
                  marginLeft: "10px",
                }}
              >
                <DatePicker
                  views={["year", "month"]}
                  label="Year and Month"
                  minDate={new Date("2012-01-01")}
                  maxDate={new Date("2024-12-31")}
                  value={selectedDateGraphe1}
                  onChange={setSelectedDateGraphe1}
                  slotProps={{
                    textField: { fullWidth: true, margin: "normal" },
                  }}
                />
              </div>

              <CardContent>
                <ChartArea
                  series={[
                    {
                      name: "Nbr.Agency Exit",
                      data: monthlyStats.exitData.map((item) => item.count),
                      axis: monthlyStats.exitData.map((item) =>
                        typeof item.month === "number"
                          ? monthNames[item.month - 1]
                          : "Unknown"
                      ), 
                      color: "#FF5733",
                    },
                    {
                      name: "Nbr.Agency Active",
                      data: monthlyStats.activeData.map((item) => item.count),
                      axis: monthlyStats.activeData.map((item) =>
                        typeof item.month === "number"
                          ? monthNames[item.month - 1]
                          : "Unknown"
                      ), 
                      color: "rgb(0, 167, 111)",
                    },
                  ]}
                />
              </CardContent>
            </Card>
          </Grid>

          <Grid xs={12} md={4} lg={4}>
            <Card sx={{ height: "100%",boxShadow: 'none'  }}>
              <CardHeader title="New Account Agency" />
              <AggencyNoApproved />
            </Card>
          </Grid>

          <Grid xs={12} md={9} lg={9}>
            <Card sx={{boxShadow: 'none'  }}>
              <CardHeader title="List Users" />
              <AllUserView />
            </Card>
          </Grid>

          <Grid xs={12} md={3} lg={3}>
  <Stack spacing={5}>
    <AppWidget
      title="Manager"
      total={roleCounts.Manager} 
      icon="solar:user-rounded-bold"
      color="success"
      chart={{
        series: [roleCounts.Manager], 
      }}
    />
    <AppWidget
      title="Client"
      total={roleCounts.Client} 
      icon="solar:user-rounded-bold"
      color="warning"
      chart={{
        series: [roleCounts.Client], 
      }}
    />
    <AppWidget
      title="Collaborator"
      total={roleCounts.Collaborator} 
      icon="solar:user-rounded-bold"
      color="info"
      chart={{
        series: [roleCounts.Collaborator],
      }}
    />
    <AppWidget
      title="Unattached User"
      total={roleCounts.UnattachedUser} 
      icon="solar:user-rounded-bold"
      color="primary"
      chart={{
        series: [roleCounts.UnattachedUser], 
      }}
    />
  </Stack>
</Grid>

          <Grid xs={12} md={12} lg={12}>
            <AgencyListView admin={true} />
          </Grid>
        </Grid>
      </Container>
    </LocalizationProvider>
  );
}
