import React, { useState } from 'react';
import {
  TextField,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  SelectChangeEvent,
} from '@mui/material';
import { BugReport } from '@mui/icons-material';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { issuesApi } from '../../services/issues';
import { useNotification } from '../../contexts/NotificationContext';
import { FormCard } from '../templates/FormCard';
import { WidgetCard } from '../templates/WidgetCard';
import { FormSkeleton } from '../templates/SkeletonPresets';

const PRIO_OPTIONS = [
  { value: 'niedrig', label: 'Niedrig' },
  { value: 'mittel', label: 'Mittel' },
  { value: 'hoch', label: 'Hoch' },
];

const IssueQuickAddWidget: React.FC = () => {
  const [titel, setTitel] = useState('');
  const [typId, setTypId] = useState<number | ''>('');
  const [prioritaet, setPrioritaet] = useState<string>('mittel');
  const { showSuccess, showError } = useNotification();
  const queryClient = useQueryClient();

  const { data: types = [], isLoading: typesLoading } = useQuery({
    queryKey: ['issue-types'],
    queryFn: issuesApi.getTypes,
    staleTime: 10 * 60 * 1000,
  });

  const activeTypes = types.filter((t) => t.aktiv);
  const defaultTypId = activeTypes[0]?.id;

  const mutation = useMutation({
    mutationFn: () =>
      issuesApi.createIssue({
        titel: titel.trim(),
        typ_id: typId !== '' ? (typId as number) : defaultTypId,
        prioritaet,
      }),
    onSuccess: () => {
      showSuccess('Issue erstellt');
      setTitel('');
      setTypId('');
      setPrioritaet('mittel');
      queryClient.invalidateQueries({ queryKey: ['issues'] });
    },
    onError: () => {
      showError('Issue konnte nicht erstellt werden');
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!titel.trim()) return;
    mutation.mutate();
  };

  if (typesLoading) {
    return (
      <WidgetCard
        title="Issue melden"
        icon={<BugReport />}
        isLoading
        skeleton={<FormSkeleton />}
      />
    );
  }

  return (
    <FormCard
      title="Issue melden"
      icon={<BugReport />}
      isSubmitting={mutation.isPending}
      onSubmit={handleSubmit}
      submitLabel="Melden"
    >
      <TextField
        fullWidth
        size="small"
        label="Titel"
        value={titel}
        onChange={(e) => setTitel(e.target.value)}
        inputProps={{ maxLength: 255 }}
        autoComplete="off"
      />

      <FormControl fullWidth size="small">
        <InputLabel>Typ</InputLabel>
        <Select
          value={typId}
          label="Typ"
          onChange={(e: SelectChangeEvent<number | ''>) =>
            setTypId(e.target.value as number | '')
          }
        >
          {activeTypes.map((t) => (
            <MenuItem key={t.id} value={t.id}>
              {t.name}
            </MenuItem>
          ))}
        </Select>
      </FormControl>

      <FormControl fullWidth size="small">
        <InputLabel>Priorität</InputLabel>
        <Select
          value={prioritaet}
          label="Priorität"
          onChange={(e: SelectChangeEvent<string>) => setPrioritaet(e.target.value)}
        >
          {PRIO_OPTIONS.map((p) => (
            <MenuItem key={p.value} value={p.value}>
              {p.label}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </FormCard>
  );
};

export default IssueQuickAddWidget;
