import React, { useState } from 'react';
import Button from '@mui/material/Button';
import CircularProgress from '@mui/material/CircularProgress';
import AssignmentIndIcon from '@mui/icons-material/AssignmentInd';
import { Trans } from '@lingui/macro';
import { useClassSessions } from '../../hooks/useClassSessions';
import type { ResolverReport } from '../../types/class';

interface KlassenZuweisenButtonProps {
  berId: number;
  year: number;
  weekIso: number;
  onResolved: (report: ResolverReport) => void;
}

const KlassenZuweisenButton: React.FC<KlassenZuweisenButtonProps> = ({
  berId,
  year,
  weekIso,
  onResolved,
}) => {
  const [running, setRunning] = useState<boolean>(false);
  const { resolveWeek } = useClassSessions({
    berId,
    from: '',
    to: '',
    enabled: true,
  });

  const handleClick = async (): Promise<void> => {
    setRunning(true);
    try {
      const report: ResolverReport = await resolveWeek(year, weekIso);
      onResolved(report);
    } catch {
      // toast shown by hook
    } finally {
      setRunning(false);
    }
  };

  return (
    <Button
      variant="outlined"
      size="small"
      startIcon={running ? <CircularProgress size={14} /> : <AssignmentIndIcon />}
      onClick={handleClick}
      disabled={running}
    >
      <Trans>Klassen zuweisen</Trans>
    </Button>
  );
};

export default KlassenZuweisenButton;
