import React, { useState } from 'react';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import Tooltip from '@mui/material/Tooltip';
import QrCode2Icon from '@mui/icons-material/QrCode2';
import CalendarMonthIcon from '@mui/icons-material/CalendarMonth';
import AssessmentIcon from '@mui/icons-material/Assessment';
import SmartphoneIcon from '@mui/icons-material/Smartphone';
import TouchAppIcon from '@mui/icons-material/TouchApp';
import { t } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import axios from 'axios';
import { useToast } from '../shared/ToastProvider';
import WidgetWrapper from './WidgetWrapper';
import { LinkedDevice } from '../../types/dashboard';
import { handleApiError } from '../../utils/errorHandler';

// Import existing modals
import UserDevicePairingModal from '../UserDevicePairingModal';
import UserShiftCalendarModal from '../UserShiftCalendarModal';
import UserStatisticsModal from '../UserStatisticsModal';
import UserDeviceInfoModal from '../UserDeviceInfoModal';

interface ActionsWidgetProps {
  userId: number;
  userName: string;
  linkedDevice?: LinkedDevice | null;
  loading?: boolean;
  onDeviceUnlinked?: () => void;
}

const ActionsWidget: React.FC<ActionsWidgetProps> = ({
  userId,
  userName,
  linkedDevice,
  loading = false,
  onDeviceUnlinked,
}) => {
  const { i18n } = useLingui();
  const toast = useToast();

  // Modal states
  const [pairingModalOpen, setPairingModalOpen] = useState(false);
  const [shiftsModalOpen, setShiftsModalOpen] = useState(false);
  const [statsModalOpen, setStatsModalOpen] = useState(false);
  const [deviceInfoModalOpen, setDeviceInfoModalOpen] = useState(false);

  // Handle device unlink - make API call then notify parent
  const handleUnlinkDevice = async () => {
    try {
      await axios.delete(`/zeiterfassung/users/${userId}/device`);
      setDeviceInfoModalOpen(false);
      if (onDeviceUnlinked) {
        onDeviceUnlinked();
      }
    } catch (err) {
      const errorMessage = handleApiError('ActionsWidget.handleUnlinkDevice', err);
      toast.error({ title: i18n._(t`Fehler`), description: errorMessage });
    }
  };

  // Action button definitions - device icon comes right after QR code when linked
  const quickActions = [
    {
      id: 'qr-pair',
      icon: <QrCode2Icon />,
      label: i18n._(t`Gerät koppeln`),
      onClick: () => setPairingModalOpen(true),
      color: 'primary' as const,
    },
    // Device unlink button - only shown when device is linked (right after QR code)
    ...(linkedDevice
      ? [
          {
            id: 'device-info',
            icon: <SmartphoneIcon />,
            label: i18n._(t`Gerät entkoppeln`),
            onClick: () => setDeviceInfoModalOpen(true),
            color: 'success' as const,
          },
        ]
      : []),
    {
      id: 'shifts',
      icon: <CalendarMonthIcon />,
      label: i18n._(t`Schichten`),
      onClick: () => setShiftsModalOpen(true),
      color: 'info' as const,
    },
    {
      id: 'stats',
      icon: <AssessmentIcon />,
      label: i18n._(t`Statistiken`),
      onClick: () => setStatsModalOpen(true),
      color: 'success' as const,
    },
  ];

  return (
    <>
      <WidgetWrapper
        title={i18n._(t`Aktionen`)}
        icon={<TouchAppIcon />}
        loading={loading}
      >
        <Box sx={{ p: 2 }}>
          {/* Quick Action Buttons */}
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'space-around',
              gap: 1,
            }}
          >
            {quickActions.map((action) => (
              <Tooltip key={action.id} title={action.label}>
                <Box
                  sx={{
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    gap: 0.5,
                  }}
                >
                  <IconButton
                    onClick={action.onClick}
                    sx={{
                      bgcolor: `${action.color}.main`,
                      color: '#fff',
                      borderRadius: 2,
                      '&:hover': { bgcolor: `${action.color}.dark` },
                    }}
                  >
                    {action.icon}
                  </IconButton>
                  <Typography
                    variant="caption"
                    sx={{
                      textAlign: 'center',
                      fontSize: '0.7rem',
                      fontWeight: 500,
                      color: 'text.secondary',
                    }}
                  >
                    {action.label}
                  </Typography>
                </Box>
              </Tooltip>
            ))}
          </Box>
        </Box>
      </WidgetWrapper>

      {/* Modals */}
      <UserDevicePairingModal
        open={pairingModalOpen}
        onClose={() => setPairingModalOpen(false)}
        userId={userId}
        userName={userName}
      />

      <UserShiftCalendarModal
        open={shiftsModalOpen}
        onClose={() => setShiftsModalOpen(false)}
        userId={userId}
        userName={userName}
        allowEdit={false}
      />

      <UserStatisticsModal
        open={statsModalOpen}
        onClose={() => setStatsModalOpen(false)}
        userId={userId}
        userName={userName}
      />

      {linkedDevice && (
        <UserDeviceInfoModal
          open={deviceInfoModalOpen}
          onClose={() => setDeviceInfoModalOpen(false)}
          userName={userName}
          device={{
            device_id: linkedDevice.deviceId,
            device_name: linkedDevice.deviceName,
            device_type: linkedDevice.deviceType,
            device_model: linkedDevice.deviceModel,
            paired_at: linkedDevice.pairedAt,
            last_active_at: linkedDevice.lastActiveAt,
          }}
          onUnlink={handleUnlinkDevice}
        />
      )}
    </>
  );
};

export default React.memo(ActionsWidget, (prevProps, nextProps) => {
  return (
    prevProps.userId === nextProps.userId &&
    prevProps.userName === nextProps.userName &&
    prevProps.loading === nextProps.loading &&
    prevProps.linkedDevice?.deviceId === nextProps.linkedDevice?.deviceId
  );
});
