import React, { isValidElement, useState } from 'react';
import {
  AppBar,
  Box,
  Chip,
  Dialog,
  DialogContent,
  LinearProgress,
  Stack,
  Toolbar,
  Typography,
} from '@mui/material';
import { LoadingButton } from '@mui/lab';
import { useGridApiRef, GridColDef } from '@mui/x-data-grid-premium';
import dayjs from 'dayjs';

// 🔧 utils kecil: hitung progress %
const getProgressPercent = (total: number, processed: number): number => {
  if (total <= 0) return 0;
  const percent = Math.round((processed / total) * 100);
  return Math.min(percent, 100);
};

// 🚪 Komponen tombol close (kamu bisa ganti pakai punya existing)
import CloseIcon from '@mui/icons-material/Close';
import IconButton from '@mui/material/IconButton';

interface CloseButtonDialogProps {
  disabled?: boolean;
  onClick?: () => void;
}
const CloseButtonDialog: React.FC<CloseButtonDialogProps> = ({ disabled, onClick }) => (
  <IconButton color="inherit" onClick={onClick} disabled={disabled}>
    <CloseIcon />
  </IconButton>
);

export interface DetailProgressRow {
  id?: string | number;
  kode?: string;
  nama?: string;
  message?: string;
  status?: 'success' | 'fail' | 'pending';
}

export interface DialogProgressBarProps {
  isOpen: boolean;
  handleClose: () => void;
  status: string;
  numberOfData: number;
  numberOfDataProcessed: number;
  numberOfDataSuccess: number;
  numberOfDataFail: number;
  isDetailUpload?: boolean;
  detailProgressTableData?: DetailProgressRow[];
  columns?: GridColDef[]; // opsional jika ingin custom table columns
}

export default function DialogProgressBar({
  isOpen,
  handleClose,
  status,
  numberOfData,
  numberOfDataProcessed,
  numberOfDataSuccess,
  numberOfDataFail,
  isDetailUpload = false,
  detailProgressTableData = [],
  columns,
}: DialogProgressBarProps) {
  const apiRef = useGridApiRef();
  const [isLoadingExportExcel, setIsLoadingExportExcel] = useState(false);

  const progress = getProgressPercent(numberOfData, numberOfDataProcessed);
  const isInProgress = progress < 100 && progress > 0;

  const handleExportExcel = async () => {
    if (!apiRef.current) return;
    setIsLoadingExportExcel(true);

    await apiRef.current.exportDataAsExcel({
      fileName: `InformasiProgress_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}`,
      fields: ['kode', 'nama', 'message'],
      includeHeaders: true,
    });

    setIsLoadingExportExcel(false);
  };

  return (
    <Dialog
      fullWidth
      maxWidth="lg"
      scroll="body"
      open={isOpen}
      onClose={handleClose}
      sx={{
        '& .MuiDialog-paper': { overflow: 'hidden' },
      }}
    >
      <AppBar position="static" elevation={0}>
        <Toolbar sx={{ justifyContent: 'flex-end' }}>
          <CloseButtonDialog disabled={isInProgress} onClick={handleClose} />
        </Toolbar>
      </AppBar>

      <DialogContent>
        {/* Header status */}
        <Box textAlign="center" mt={2}>
          <Typography fontWeight={600} variant="h5">
            {status}
          </Typography>
        </Box>

        {/* Progress bar */}
        <Stack direction="row" alignItems="center" mt={2} spacing={1}>
          <LinearProgress
            variant="determinate"
            sx={{ height: '10px', borderRadius: '5px', flex: 1 }}
            value={progress}
          />
          <Typography fontWeight={600}>{progress}%</Typography>
        </Stack>

        {/* Summary chip */}
        <Stack
          direction="row"
          spacing={2}
          justifyContent="center"
          alignItems="center"
          mt={3}
          mb={2}
        >
          <Typography variant="h6">Total: {numberOfData}</Typography>
          <Chip
            size="medium"
            label={<Typography variant="h6">Success: {numberOfDataSuccess}</Typography>}
            color="success"
          />
          <Chip
            size="medium"
            label={<Typography variant="h6">Failed: {numberOfDataFail}</Typography>}
            color="error"
          />

          {/* Download Excel */}
          {isDetailUpload && progress === 100 && detailProgressTableData.length > 0 && (
            <LoadingButton
              loading={isLoadingExportExcel}
              variant="contained"
              color="primary"
              onClick={handleExportExcel}
              sx={{ borderRadius: 2 }}
            >
              Download Detail
            </LoadingButton>
          )}
        </Stack>

        {/* Table section */}
        {isDetailUpload && progress === 100 && detailProgressTableData.length > 0 && (
          <Box sx={{ mt: 2 }}>
            <Typography fontWeight={600} mb={1}>
              Detail Progress
            </Typography>
            <div style={{ height: 400, width: '100%' }}>
              {/* Kamu bisa ganti ke komponen table kamu sendiri */}
              <Box sx={{ border: '1px solid #ddd', borderRadius: 2, p: 1 }}>
                {/* DataGrid Premium bawaan */}
                {/* Kalau kamu punya PexDataGrid, tinggal ganti aja di sini */}
                <div>🔧 Integrasikan DataGridPremium di sini</div>
              </Box>
            </div>
          </Box>
        )}
      </DialogContent>
    </Dialog>
  );
}
