import React, { useEffect, useState } from "react";
import {
  Timeline,
  TimelineDot,
  TimelineItem,
  TimelineSeparator,
  TimelineConnector,
  TimelineContent,
  timelineItemClasses,
} from "@mui/lab";
import {
  Typography,
  Divider,
  Box,
  Button,
  MenuItem,
  IconButton,
} from "@mui/material";
import Iconify from "@/shared/components/iconify";
import CustomPopover, { usePopover } from "@/shared/components/custom-popover";
import { ConfirmDialog } from "@/components/custom-dialog";
import DialogAgency from "./view-detail-agency-no-approved";

import { fDateTime } from "@/utils/format-time";
import axiosInstancee from "@/utils/axios";
import { enqueueSnackbar } from "@/shared/components/snackbar";
import { useBoolean } from "@/hooks";
import { IAgencyNotification } from "@/shared/types/agency";
import AgencyListDialog from "@/components/custom-dialog/AgencyListDialog";
import { useAgencyUpdates } from "@/contexts/agency-updates-context";

export default function AgencyNotificationTimeline() {
  const [agencyNotifications, setAgencyNotifications] = useState<
    IAgencyNotification[]
  >([]);
  const [viewAllOpen, setViewAllOpen] = useState(false);

  const fetchNotifications = async () => {
    try {
      const response = await axiosInstancee.get("/api/user/pending-agencies");
      setAgencyNotifications(response.data);
    } catch (error) {
      console.error("Failed to fetch notifications:", error);
      enqueueSnackbar("Failed to fetch notifications", { variant: "error" });
    }
  };

  useEffect(() => {
    fetchNotifications();
  }, []);

  const removeNotification = (agencyId: string) => {
    setAgencyNotifications((prevNotifications) =>
      prevNotifications.filter(
        (notification) => notification.agencyId !== agencyId
      )
    );
  };

  return (
    <>
      <Timeline
        sx={{
          m: 0,
          p: 3,
          [`& .${timelineItemClasses.root}:before`]: { flex: 0, padding: 0 },
        }}
      >
        {agencyNotifications.slice(0, 6).map((item, index) => (
          <OrderItem
            key={item.id}
            item={item}
            lastTimeline={index === agencyNotifications.length - 1}
            onRemove={removeNotification}
          />
        ))}
        <Divider sx={{ borderStyle: "dashed" }} />
      </Timeline>
      <Box sx={{ p: 2, textAlign: "right" }}>
        <Button
          size="small"
          color="inherit"
          onClick={() => setViewAllOpen(true)}
          endIcon={
            <Iconify
              icon="eva:arrow-ios-forward-fill"
              width={18}
              sx={{ ml: -0.5 }}
            />
          }
        >
          View All
        </Button>
      </Box>

      {/* Dialog to view all agencies */}
      <AgencyListDialog
        open={viewAllOpen}
        onClose={() => setViewAllOpen(false)}
        agencies={agencyNotifications}
        onRemove={removeNotification}
        refreshList={fetchNotifications}
      />
    </>
  );
}

type OrderItemProps = {
  item: IAgencyNotification;
  lastTimeline: boolean;
  onRemove: (agencyId: string) => void;
};

function OrderItem({ item, lastTimeline, onRemove }: OrderItemProps) {
  const confirm = useBoolean();
  const view = useBoolean();
  const popover = usePopover();
  const { refreshAgencyList } = useAgencyUpdates();

  const handleApprove = async (agencyId: string) => {
    try {
      await axiosInstancee.post(`/api/user/${agencyId}/approve`);
      enqueueSnackbar("Agency approved successfully!", { variant: "success" });
      onRemove(agencyId);
      refreshAgencyList();
      popover.onClose();
    } catch (error) {
      console.error("Error approving agency:", error);
      enqueueSnackbar("Failed to approve agency", { variant: "error" });
    }
  };

  const handleReject = async (agencyId: string) => {
    try {
      await axiosInstancee.post(`/api/user/${agencyId}/reject`);
      enqueueSnackbar("Agency rejected successfully!", { variant: "success" });
      onRemove(agencyId);
      refreshAgencyList();
      confirm.onFalse();
      popover.onClose();
    } catch (error) {
      console.error("Error rejecting agency:", error);
      enqueueSnackbar("Failed to reject agency", { variant: "error" });
    }
  };

  return (
    <TimelineItem>
      <TimelineSeparator>
        <TimelineDot color="warning" />
        {!lastTimeline && <TimelineConnector />}
      </TimelineSeparator>

      <TimelineContent
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <Box>
          <Typography variant="subtitle2">{item.agencyName}</Typography>
          <Typography variant="caption" sx={{ color: "text.secondary" }}>
            {fDateTime(convertDateArrayToString(item.createDate))}
          </Typography>
        </Box>

        <IconButton
          color={popover.open ? "inherit" : "default"}
          onClick={popover.onOpen}
        >
          <Iconify icon="eva:more-vertical-fill" />
        </IconButton>

        <CustomPopover
          open={popover.open}
          onClose={popover.onClose}
          arrow="right-top"
        >
          <MenuItem onClick={() => handleApprove(item.agencyId)}>
            <Iconify icon="eva:checkmark-circle-2-fill" />
            Approve
          </MenuItem>
          <MenuItem
            onClick={() => {
              view.onTrue();
              popover.onClose();
            }}
          >
            <Iconify icon="solar:eye-bold" />
            View
          </MenuItem>
          <Divider sx={{ borderStyle: "dashed" }} />
          <MenuItem
            onClick={() => confirm.onTrue()}
            sx={{ color: "error.main" }}
          >
            <Iconify icon="solar:trash-bin-trash-bold" />
            Reject
          </MenuItem>
        </CustomPopover>

        <ConfirmDialog
          open={confirm.value}
          onClose={confirm.onFalse}
          title="Reject"
          content="Are you sure you want to reject this agency?"
          action={
            <Button
              variant="contained"
              color="error"
              onClick={() => handleReject(item.agencyId)}
            >
              Reject
            </Button>
          }
        />

        <DialogAgency open={view.value} onClose={view.onFalse} agency={item} />
      </TimelineContent>
    </TimelineItem>
  );
}

function convertDateArrayToString(dateArray: number[]): string {
  try {
    // dateArray format: [year, month, day, hour, minute, second, nano]
    const [year, month, day, hour, minute, second] = dateArray;
    
    // Create date using UTC to avoid timezone issues
    const date = Date.UTC(year, month - 1, day, hour, minute, second);
    return new Date(date).toISOString();
  } catch (error) {
    console.error('Invalid date array:', dateArray);
    // Return a fallback date or current date if conversion fails
    return new Date().toISOString();
  }
}