import React, { useState } from 'react';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import LinearProgress from '@mui/material/LinearProgress';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
import Chip from '@mui/material/Chip';
import Divider from '@mui/material/Divider';
import Accordion from '@mui/material/Accordion';
import AccordionSummary from '@mui/material/AccordionSummary';
import AccordionDetails from '@mui/material/AccordionDetails';
import CloseIcon from '@mui/icons-material/Close';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import CodeIcon from '@mui/icons-material/Code';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import TrendingDownIcon from '@mui/icons-material/TrendingDown';
import TrendingUpIcon from '@mui/icons-material/TrendingUp';
import { Trans, t } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import { format, parseISO } from 'date-fns';
import { de } from 'date-fns/locale';

interface CapacityAnalysisData {
  runId: string;
  createdAtISO: string;
  window: {
    startISO: string;
    endISO: string;
  };
  reserveTargetPct: number;
  overall: {
    requiredCoveragePct: number;
    niceCoveragePct: number;
    reserveCoveragePct: number;
    progressScore: number;
  };
  roles: Array<{
    roleId: number;
    requiredMinutes: number;
    niceMinutes: number;
    capacityMinutes: number;
    requiredShortfallMinutes: number;
    niceShortfallMinutes: number;
    fteNeededForRequired: number;
    fteNeededForNice: number;
    fteNeededTotal: number;
  }>;
  weeks: Array<{
    weekStartISO: string;
    requiredMinutes: number;
    niceMinutes: number;
    capacityMinutes: number;
  }>;
  assumptions?: string[];
  input_payload?: {
    department_id: number;
    year: number;
    month: number;
    users: Array<{
      user_id: number;
      name: string;
      roles: number[];
      required_hours_per_week: number;
    }>;
    shift_templates: Array<any>;
  };
}

interface CapacityAnalysisModalProps {
  open: boolean;
  onClose: () => void;
  data: CapacityAnalysisData | null;
  roleNames?: Record<number, string>;
}

const CapacityAnalysisModal: React.FC<CapacityAnalysisModalProps> = ({
  open,
  onClose,
  data,
  roleNames = {},
}) => {
  const { i18n } = useLingui();

  if (!data) {
    return null;
  }

  const formatMinutesToHours = (minutes: number): string => {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return `${hours}h ${mins}m`;
  };

  const getPercentageColor = (pct: number): string => {
    if (pct >= 0.9) return 'success';
    if (pct >= 0.7) return 'warning';
    return 'error';
  };

  const getPercentageColorRaw = (pct: number): string => {
    if (pct >= 0.9) return '#4caf50';
    if (pct >= 0.7) return '#ff9800';
    return '#f44336';
  };

  const renderMetricCard = (
    title: string,
    value: number,
    icon: React.ReactNode,
    color: string,
    subtitle?: string
  ) => (
    <Box
      sx={{
        backgroundColor: 'background.paper',
        borderRadius: 2,
        p: 2,
        border: 1,
        borderColor: 'divider',
      }}
    >
      <Box display="flex" alignItems="center" justifyContent="space-between" mb={1}>
        <Typography variant="body2" color="text.secondary" fontWeight="medium">
          {title}
        </Typography>
        <Box sx={{ color }}>{icon}</Box>
      </Box>
      <Typography variant="h4" fontWeight="bold" sx={{ color }}>
        {Math.round(value * 100)}%
      </Typography>
      <LinearProgress
        variant="determinate"
        value={value * 100}
        sx={{
          mt: 1,
          height: 8,
          borderRadius: 1,
          backgroundColor: 'action.hover',
          '& .MuiLinearProgress-bar': {
            backgroundColor: color,
          },
        }}
      />
      {subtitle && (
        <Typography variant="caption" color="text.secondary" sx={{ mt: 0.5 }}>
          {subtitle}
        </Typography>
      )}
    </Box>
  );

  return (
    <Dialog open={open} onClose={onClose} maxWidth="lg" fullWidth>
      <DialogTitle>
        <Box display="flex" alignItems="center" justifyContent="space-between">
          <Box>
            <Typography variant="h5" fontWeight="bold">
              <Trans>Kapazitätsanalyse</Trans>
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>
              {format(parseISO(data.window.startISO), 'dd. MMM yyyy', { locale: de })} –{' '}
              {format(parseISO(data.window.endISO), 'dd. MMM yyyy', { locale: de })}
            </Typography>
          </Box>
          <IconButton onClick={onClose} size="small">
            <CloseIcon />
          </IconButton>
        </Box>
      </DialogTitle>

      <DialogContent>
        {/* Overall Metrics */}
        <Box sx={{ mb: 3 }}>
          <Box display="grid" gridTemplateColumns="repeat(auto-fit, minmax(200px, 1fr))" gap={2}>
            {renderMetricCard(
              i18n._(t`Erforderliche Deckung`),
              data.overall.requiredCoveragePct,
              data.overall.requiredCoveragePct >= 0.9 ? (
                <CheckCircleIcon />
              ) : (
                <TrendingDownIcon />
              ),
              getPercentageColorRaw(data.overall.requiredCoveragePct)
            )}

            {renderMetricCard(
              i18n._(t`Nice-to-Have`),
              data.overall.niceCoveragePct,
              data.overall.niceCoveragePct >= 0.7 ? (
                <TrendingUpIcon />
              ) : (
                <TrendingDownIcon />
              ),
              getPercentageColorRaw(data.overall.niceCoveragePct)
            )}

            {renderMetricCard(
              i18n._(t`Reserve-Puffer`),
              data.overall.reserveCoveragePct,
              data.overall.reserveCoveragePct >= 0.7 ? (
                <TrendingUpIcon />
              ) : (
                <TrendingDownIcon />
              ),
              getPercentageColorRaw(data.overall.reserveCoveragePct)
            )}

            <Box
              sx={{
                backgroundColor: 'primary.main',
                color: 'primary.contrastText',
                borderRadius: 2,
                p: 2,
                border: 1,
                borderColor: 'primary.dark',
              }}
            >
              <Box display="flex" alignItems="center" justifyContent="space-between" mb={1}>
                <Typography variant="body2" fontWeight="medium">
                  <Trans>Gesamtbewertung</Trans>
                </Typography>
                <TrendingUpIcon />
              </Box>
              <Typography variant="h4" fontWeight="bold">
                {Math.round(data.overall.progressScore * 100)}%
              </Typography>
              <Typography variant="caption" sx={{ mt: 0.5, display: 'block' }}>
                <Trans>Gewichteter Composite</Trans>
              </Typography>
            </Box>
          </Box>
        </Box>

        <Divider sx={{ my: 3 }} />

        {/* Staffing by Role Table */}
        <Box sx={{ mb: 3 }}>
          <Typography variant="h6" fontWeight="bold" gutterBottom>
            <Trans>Personalbedarf nach Rolle</Trans>
          </Typography>
          <TableContainer component={Paper} variant="outlined">
            <Table size="small">
              <TableHead>
                <TableRow sx={{ backgroundColor: 'action.hover' }}>
                  <TableCell>
                    <strong>
                      <Trans>Rolle</Trans>
                    </strong>
                  </TableCell>
                  <TableCell align="right">
                    <strong>
                      <Trans>Erforderlich</Trans>
                    </strong>
                  </TableCell>
                  <TableCell align="right">
                    <strong>
                      <Trans>Nice</Trans>
                    </strong>
                  </TableCell>
                  <TableCell align="right">
                    <strong>
                      <Trans>Kapazität</Trans>
                    </strong>
                  </TableCell>
                  <TableCell align="right">
                    <strong>
                      <Trans>Fehlbetrag</Trans>
                    </strong>
                  </TableCell>
                  <TableCell align="right">
                    <strong>
                      <Trans>FTE benötigt</Trans>
                    </strong>
                  </TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {data.roles.map((role) => {
                  const hasShortfall =
                    role.requiredShortfallMinutes > 0 || role.niceShortfallMinutes > 0;
                  const totalShortfall =
                    role.requiredShortfallMinutes + role.niceShortfallMinutes;

                  return (
                    <TableRow
                      key={role.roleId}
                      sx={{
                        '&:hover': { backgroundColor: 'action.hover' },
                        backgroundColor: hasShortfall ? 'error.lighter' : 'inherit',
                      }}
                    >
                      <TableCell>
                        <Typography variant="body2" fontWeight="medium">
                          {roleNames[role.roleId] || `Role ${role.roleId}`}
                        </Typography>
                      </TableCell>
                      <TableCell align="right">
                        <Typography variant="body2" color="text.secondary">
                          {formatMinutesToHours(role.requiredMinutes)}
                        </Typography>
                      </TableCell>
                      <TableCell align="right">
                        <Typography variant="body2" color="text.secondary">
                          {formatMinutesToHours(role.niceMinutes)}
                        </Typography>
                      </TableCell>
                      <TableCell align="right">
                        <Typography variant="body2" color="text.secondary">
                          {formatMinutesToHours(role.capacityMinutes)}
                        </Typography>
                      </TableCell>
                      <TableCell align="right">
                        {hasShortfall ? (
                          <Typography
                            variant="body2"
                            fontWeight="medium"
                            color="error"
                          >
                            {formatMinutesToHours(totalShortfall)}
                          </Typography>
                        ) : (
                          <Typography variant="body2" color="success.main">
                            —
                          </Typography>
                        )}
                      </TableCell>
                      <TableCell align="right">
                        {role.fteNeededTotal > 0 ? (
                          <Chip
                            label={role.fteNeededTotal.toFixed(1)}
                            size="small"
                            color="warning"
                          />
                        ) : (
                          <Typography variant="body2" color="success.main">
                            —
                          </Typography>
                        )}
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </TableContainer>
        </Box>

        <Divider sx={{ my: 3 }} />

        {/* Weekly Breakdown */}
        <Box sx={{ mb: 3 }}>
          <Typography variant="h6" fontWeight="bold" gutterBottom>
            <Trans>Wöchentliche Aufschlüsselung</Trans>
          </Typography>
          <Box display="flex" flexDirection="column" gap={2}>
            {data.weeks.map((week) => {
              const totalDemand = week.requiredMinutes + week.niceMinutes;
              const coveragePct = totalDemand > 0 ? week.capacityMinutes / totalDemand : 1;
              const requiredCoveragePct =
                week.requiredMinutes > 0
                  ? Math.min(week.capacityMinutes / week.requiredMinutes, 1)
                  : 1;

              return (
                <Box key={week.weekStartISO}>
                  <Box display="flex" justifyContent="space-between" alignItems="center" mb={1}>
                    <Typography variant="body2" fontWeight="medium">
                      <Trans>Woche vom</Trans>{' '}
                      {format(parseISO(week.weekStartISO), 'dd. MMM yyyy', { locale: de })}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      {formatMinutesToHours(week.capacityMinutes)} /{' '}
                      {formatMinutesToHours(totalDemand)}
                    </Typography>
                  </Box>
                  <Box display="flex" height={32} borderRadius={1} overflow="hidden">
                    <Box
                      sx={{
                        backgroundColor: getPercentageColorRaw(requiredCoveragePct),
                        width: `${requiredCoveragePct * 100}%`,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        color: 'white',
                        fontSize: '0.75rem',
                        fontWeight: 'bold',
                      }}
                    >
                      {Math.round(requiredCoveragePct * 100)}%
                    </Box>
                    {coveragePct < 1 && (
                      <Box
                        sx={{
                          flex: 1,
                          backgroundColor: 'error.lighter',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          color: 'error.main',
                          fontSize: '0.75rem',
                          fontWeight: 'bold',
                        }}
                      >
                        <Trans>Lücke</Trans> {Math.round((1 - coveragePct) * 100)}%
                      </Box>
                    )}
                  </Box>
                </Box>
              );
            })}
          </Box>
        </Box>

        {/* Assumptions */}
        {data.assumptions && data.assumptions.length > 0 && (
          <Box sx={{ mt: 3, p: 2, backgroundColor: 'action.hover', borderRadius: 2 }}>
            <Typography variant="body2" fontWeight="medium" gutterBottom>
              <Trans>Annahmen</Trans>
            </Typography>
            <Box component="ul" sx={{ m: 0, pl: 2 }}>
              {data.assumptions.map((assumption, idx) => (
                <Typography
                  key={idx}
                  component="li"
                  variant="caption"
                  color="text.secondary"
                  sx={{ mb: 0.5 }}
                >
                  {assumption}
                </Typography>
              ))}
            </Box>
          </Box>
        )}

        {/* Input Data Section */}
        {data.input_payload && (
          <Box sx={{ mt: 3 }}>
            <Accordion>
              <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                <Box display="flex" alignItems="center" gap={1}>
                  <CodeIcon fontSize="small" />
                  <Typography variant="body2" fontWeight="medium">
                    <Trans>Eingangsdaten anzeigen</Trans> ({data.input_payload.users.length}{' '}
                    <Trans>Benutzer</Trans>, {data.input_payload.shift_templates.length}{' '}
                    <Trans>Schichtvorlagen</Trans>)
                  </Typography>
                </Box>
              </AccordionSummary>
              <AccordionDetails>
                <Box sx={{ maxHeight: 400, overflow: 'auto' }}>
                  {/* Users Summary */}
                  <Typography variant="subtitle2" gutterBottom>
                    <Trans>Benutzer</Trans> ({data.input_payload.users.length})
                  </Typography>
                  <TableContainer component={Paper} variant="outlined" sx={{ mb: 2 }}>
                    <Table size="small">
                      <TableHead>
                        <TableRow>
                          <TableCell>
                            <Trans>Name</Trans>
                          </TableCell>
                          <TableCell>
                            <Trans>Rollen</Trans>
                          </TableCell>
                          <TableCell align="right">
                            <Trans>Std./Woche</Trans>
                          </TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {data.input_payload.users.map((user) => (
                          <TableRow key={user.user_id}>
                            <TableCell>{user.name}</TableCell>
                            <TableCell>
                              {user.roles.map((roleId) => (
                                <Chip
                                  key={roleId}
                                  label={roleNames[roleId] || `Role ${roleId}`}
                                  size="small"
                                  sx={{ mr: 0.5, mb: 0.5 }}
                                />
                              ))}
                            </TableCell>
                            <TableCell align="right">
                              {user.required_hours_per_week}h
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </TableContainer>

                  {/* Shift Templates Summary */}
                  <Typography variant="subtitle2" gutterBottom>
                    <Trans>Schichtvorlagen</Trans> ({data.input_payload.shift_templates.length})
                  </Typography>
                  <TableContainer component={Paper} variant="outlined">
                    <Table size="small">
                      <TableHead>
                        <TableRow>
                          <TableCell>
                            <Trans>Name</Trans>
                          </TableCell>
                          <TableCell>
                            <Trans>Zeit</Trans>
                          </TableCell>
                          <TableCell align="right">
                            <Trans>Min/Max Arbeiter</Trans>
                          </TableCell>
                          <TableCell>
                            <Trans>Erforderliche Rollen</Trans>
                          </TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {data.input_payload.shift_templates.map((template) => (
                          <TableRow key={template.zst_id}>
                            <TableCell>
                              <Box display="flex" alignItems="center" gap={1}>
                                <Box
                                  sx={{
                                    width: 12,
                                    height: 12,
                                    borderRadius: '50%',
                                    backgroundColor: template.zst_color,
                                  }}
                                />
                                {template.zst_name}
                              </Box>
                            </TableCell>
                            <TableCell>
                              {template.zst_start_time} - {template.zst_end_time}
                            </TableCell>
                            <TableCell align="right">
                              {template.zst_min_workers} / {template.zst_max_workers}
                            </TableCell>
                            <TableCell>
                              {template.zst_must_have_roles?.map((role: any) => (
                                <Chip
                                  key={role.role_id}
                                  label={`${roleNames[role.role_id] || `Role ${role.role_id}`} (${
                                    role.count
                                  })`}
                                  size="small"
                                  color="primary"
                                  sx={{ mr: 0.5, mb: 0.5 }}
                                />
                              ))}
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </TableContainer>
                </Box>
              </AccordionDetails>
            </Accordion>
          </Box>
        )}
      </DialogContent>
    </Dialog>
  );
};

export default CapacityAnalysisModal;
