import React from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  List,
  ListItem,
  ListItemText,
  IconButton,
  Typography,
  Divider,
  Box,
  Button,
  MenuItem,
} from '@mui/material';
import { fDateTime } from '@/utils/format-time';
import Iconify from '@/shared/components/iconify';
import { IAgencyNotification } from '@/shared/types/agency';
import { useBoolean } from '@/hooks';
import { ConfirmDialog } from './index';
import DialogAgency from '@/shared/sections/home/view-detail-agency-no-approved';
import CustomPopover, { usePopover } from '@/shared/components/custom-popover';
import axiosInstancee from '@/utils/axios';
import { enqueueSnackbar } from '@/shared/components/snackbar';
import { useAgencyUpdates } from '@/contexts/agency-updates-context';

interface AgencyListDialogProps {
  open: boolean;
  onClose: () => void;
  agencies: IAgencyNotification[];
  onRemove: (agencyId: string) => void;
  refreshList: () => void;
}

export default function AgencyListDialog({ 
  open, 
  onClose, 
  agencies,
  onRemove,
  refreshList
}: AgencyListDialogProps) {
  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();
      refreshList();
    } catch (error) {
     
      enqueueSnackbar("Failed to approve agency", { variant: "error" });
    }
  };

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

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>
        <Typography variant="h6">Pending Agencies</Typography>
      </DialogTitle>
      <DialogContent>
        <List>
          {agencies.length === 0 ? (
            <Typography variant="body2" sx={{ py: 2, textAlign: 'center' }}>
              No pending agencies
            </Typography>
          ) : (
            agencies.map((agency) => (
              <AgencyListItem 
                key={agency.id} 
                agency={agency} 
                onApprove={handleApprove}
                onReject={handleReject}
                onRemove={onRemove}
              />
            ))
          )}
        </List>
      </DialogContent>
    </Dialog>
  );
}

function AgencyListItem({ 
  agency, 
  onApprove, 
  onReject,
  onRemove 
}: { 
  agency: IAgencyNotification;
  onApprove: (agencyId: string) => void;
  onReject: (agencyId: string, closeConfirm: () => void) => void;
  onRemove: (agencyId: string) => void;
}) {
  const confirm = useBoolean();
  const view = useBoolean();
  const popover = usePopover();

  return (
    <>
      <ListItem 
        divider 
        secondaryAction={
          <IconButton
            color={popover.open ? "inherit" : "default"}
            onClick={popover.onOpen}
          >
            <Iconify icon="eva:more-vertical-fill" />
          </IconButton>
        }
      >
        <ListItemText
          primary={agency.agencyName}
          secondary={fDateTime(convertDateArrayToString(agency.createDate))}
        />
        
        <CustomPopover
          open={popover.open}
          onClose={popover.onClose}
          arrow="right-top"
        >
          <MenuItem onClick={() => onApprove(agency.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>
      </ListItem>

      <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={() => onReject(agency.agencyId, confirm.onFalse)}
          >
            Reject
          </Button>
        }
      />

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

function convertDateArrayToString(dateArray: number[]): string {
  try {
  
    const [year, month, day, hour, minute, second] = dateArray;
  
    const date = Date.UTC(year, month - 1, day, hour, minute, second);
    return new Date(date).toISOString();
  } catch (error) {
    return new Date().toISOString();
  }
}