"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, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Avatar, Chip, Button, Box, Paper, TextField, MenuItem } 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";
import { useRouter } from "next/navigation";
import { paths } from "@/routes/paths";
import SearchIcon from "@mui/icons-material/Search";
import axios from "axios";

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;
};

// Add a User type definition
type User = {
  id: number;
  firstName?: string;
  lastName?: string;
  email?: string;
  state?: string;
  role?: string;
  createDate?: any;
  picture?: string;
};

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

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

  const [recentUsers, setRecentUsers] = useState([]);
  const [isLoadingUsers, setIsLoadingUsers] = useState(false);

  const [userSearchQuery, setUserSearchQuery] = useState('');
  const [userStatusFilter, setUserStatusFilter] = useState('all');
  const [userRoleFilter, setUserRoleFilter] = useState('all');

  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(() => {
    const fetchRecentUsers = async () => {
      setIsLoadingUsers(true);
      try {
        const response = await axiosInstancee.get('/api/user/unassigned');
        const sortedUsers = response.data.sort((a: any, b: any) => {
          const dateA = new Date(a.createDate[0], a.createDate[1] - 1, a.createDate[2]);
          const dateB = new Date(b.createDate[0], b.createDate[1] - 1, b.createDate[2]);
          return dateB.getTime() - dateA.getTime();
        }).slice(0, 10);

        setRecentUsers(sortedUsers);
      } catch (error) {
        console.error('Error fetching users:', error);
      } finally {
        setIsLoadingUsers(false);
      }
    };

    fetchRecentUsers();
  }, []);

  const handleUserClick = (userId: number) => {
    router.push(`${paths.dashboard.agency.createUserAgency}?userId=${userId}`);
  };

  const formatDate = (dateArray: number[] | null | undefined) => {
    if (!dateArray || dateArray.length < 3) return 'N/A';
    const [year, month, day] = dateArray;
    return new Date(year, month - 1, day).toLocaleDateString();
  };

  // Then update the filter function with proper typing
  const filteredUsers = recentUsers.filter((user: User) => {
    const matchesSearch =
      userSearchQuery === '' ||
      user.firstName?.toLowerCase().includes(userSearchQuery.toLowerCase()) ||
      user.lastName?.toLowerCase().includes(userSearchQuery.toLowerCase()) ||
      user.email?.toLowerCase().includes(userSearchQuery.toLowerCase());

    const matchesStatus =
      userStatusFilter === 'all' ||
      user.state === userStatusFilter;

    const matchesRole =
      userRoleFilter === 'all' ||
      (userRoleFilter === 'null' && !user.role) ||
      user.role === userRoleFilter;

    return matchesSearch && matchesStatus && matchesRole;
  });

  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 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 Agency" />
              <AggencyNoApproved />
            </Card>
          </Grid>

          <Grid xs={12} md={12} lg={12}>
            <Card sx={{ height: "100%", boxShadow: 'none' }}>
              <CardHeader
                title="Recent Users"
                action={
                  <Button
                    variant="contained"
                    size="small"
                    onClick={() => router.push(paths.dashboard.user.unassigned)}
                  >
                    View All
                  </Button>
                }
              />
              <CardContent>
                <Box sx={{ mb: 2, display: 'flex', gap: 1, flexWrap: 'wrap' }}>
                  <TextField
                    size="small"
                    label="Search"
                    value={userSearchQuery}
                    onChange={(e) => setUserSearchQuery(e.target.value)}
                    InputProps={{
                      startAdornment: <SearchIcon fontSize="small" sx={{ mr: 1, color: 'text.disabled' }} />,
                    }}
                    sx={{ minWidth: 200 }}
                  />
                  <TextField
                    select
                    size="small"
                    label="Status"
                    value={userStatusFilter}
                    onChange={(e) => setUserStatusFilter(e.target.value)}
                    sx={{ minWidth: 150 }}
                  >
                    <MenuItem value="all">All</MenuItem>
                    <MenuItem value="ACTIVE">Active</MenuItem>
                    <MenuItem value="INACTIVE">Inactive</MenuItem>
                  </TextField>
                  <TextField
                    select
                    size="small"
                    label="Role"
                    value={userRoleFilter}
                    onChange={(e) => setUserRoleFilter(e.target.value)}
                    sx={{ minWidth: 150 }}
                  >
                    <MenuItem value="all">All Roles</MenuItem>
                    <MenuItem value="ADMIN">Admin</MenuItem>
                    <MenuItem value="MANAGER">Manager</MenuItem>
                    <MenuItem value="COLLABORATOR">Collaborator</MenuItem>
                    <MenuItem value="CLIENT">Client</MenuItem>
                    <MenuItem value="null">No Role</MenuItem>
                  </TextField>
                </Box>

                <TableContainer>
                  <Table size="small">
                    <TableHead>
                      <TableRow>
                        <TableCell>Name</TableCell>
                        <TableCell>Email</TableCell>
                        <TableCell>Status</TableCell>
                        <TableCell>Role</TableCell>
                        <TableCell>Created</TableCell>
                        <TableCell align="right">Actions</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {isLoadingUsers ? (
                        <TableRow>
                          <TableCell colSpan={6} align="center">Loading...</TableCell>
                        </TableRow>
                      ) : filteredUsers.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={6} align="center">No users found</TableCell>
                        </TableRow>
                      ) : (
                        filteredUsers.slice(0, 5).map((user: User) => (
                          <TableRow key={user.id}>
                            <TableCell>
                              <Box sx={{ display: 'flex', alignItems: 'center' }}>
                                <Avatar
                                  src={user.picture && !user.picture.includes('null') && !user.picture.includes('default.jpg') ? user.picture : ''}
                                  alt={`${user.firstName} ${user.lastName}`}
                                  sx={{
                                    width: 32,
                                    height: 32,
                                    mr: 1.5,
                                    bgcolor: (theme) => {
                                      const colors = [
                                        theme.palette.primary.main,
                                        theme.palette.info.main,
                                        theme.palette.success.main,
                                        theme.palette.warning.main,
                                        theme.palette.error.main,
                                      ];
                                      // Generate consistent color based on user id
                                      return colors[user.id % colors.length];
                                    }
                                  }}
                                >
                                  {user.firstName && user.lastName ? `${user.firstName[0]}${user.lastName[0]}` : '?'}
                                </Avatar>
                                <Typography variant="body2" sx={{ fontWeight: 'medium' }}>
                                  {user.firstName} {user.lastName}
                                </Typography>
                              </Box>
                            </TableCell>
                            <TableCell>{user.email}</TableCell>
                            <TableCell>
                              <Chip
                                label={user.state}
                                size="small"
                                color={user.state === 'ACTIVE' ? 'success' : 'default'}
                              />
                            </TableCell>
                            <TableCell>{user.role || 'Not assigned'}</TableCell>
                            <TableCell>{formatDate(user.createDate)}</TableCell>
                            <TableCell align="right">
                              <Button
                                size="small"
                                variant="outlined"
                                onClick={() => handleUserClick(user.id)}
                              >
                                Assign
                              </Button>
                            </TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </TableContainer>
              </CardContent>
            </Card>
          </Grid>

          <Grid xs={12} md={9} lg={9}>
            <Card sx={{ boxShadow: 'none' }}>
              <CardHeader title="List Account Agency" />
              <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}>
            <Card sx={{ boxShadow: 'none' }}>
              
              <CardContent sx={{ p: 0 }}>
                <AgencyListView admin={true} />
              </CardContent>
            </Card>
          </Grid>
        </Grid>
      </Container>
    </LocalizationProvider>
  );
}
