import { useState } from 'react';
import {
  Box, Typography, Paper, Button, TextField, MenuItem, Select, FormControl,
  InputLabel, IconButton,
} from '@mui/material';
import { ArrowBack } from '@mui/icons-material';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import DashboardLayout from '../components/dashboard/DashboardLayout';
import { useNotification } from '../contexts/NotificationContext';
import { issuesApi } from '../services/issues';
import type { CreateIssuePayload } from '../types/issue.types';

export default function IssueNeu() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { showSuccess, showError } = useNotification();

  const [form, setForm] = useState<CreateIssuePayload>({ titel: '', prioritaet: '' });

  const { data: types = [] } = useQuery({
    queryKey: ['issue-types'],
    queryFn: issuesApi.getTypes,
  });

  const { data: priorities = [] } = useQuery({
    queryKey: ['issue-priorities'],
    queryFn: issuesApi.getPriorities,
  });

  const defaultTypId = types.find(t => t.aktiv)?.id;
  const defaultPriority = priorities.find(p => p.aktiv)?.schluessel ?? 'mittel';

  const createMut = useMutation({
    mutationFn: (data: CreateIssuePayload) => issuesApi.createIssue(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['issues'] });
      showSuccess('Issue erstellt');
      navigate('/issues');
    },
    onError: () => showError('Fehler beim Erstellen'),
  });

  const handleSubmit = () => {
    createMut.mutate({
      ...form,
      typ_id: form.typ_id ?? defaultTypId,
      prioritaet: form.prioritaet || defaultPriority,
    });
  };

  return (
    <DashboardLayout>
      <Box sx={{ p: 3 }}>
        {/* Header */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 3 }}>
          <IconButton onClick={() => navigate('/issues')}>
            <ArrowBack />
          </IconButton>
          <Typography variant="h5">Neues Issue</Typography>
        </Box>

        <Paper variant="outlined" sx={{ p: 3, maxWidth: 600 }}>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <TextField
              label="Titel"
              required
              fullWidth
              value={form.titel}
              onChange={(e) => setForm({ ...form, titel: e.target.value })}
              autoFocus
            />
            <TextField
              label="Beschreibung"
              multiline
              rows={4}
              fullWidth
              value={form.beschreibung || ''}
              onChange={(e) => setForm({ ...form, beschreibung: e.target.value })}
            />
            <FormControl fullWidth>
              <InputLabel>Typ</InputLabel>
              <Select
                value={form.typ_id ?? defaultTypId ?? ''}
                label="Typ"
                onChange={(e) => setForm({ ...form, typ_id: Number(e.target.value) })}
              >
                {types.filter(t => t.aktiv).map(t => (
                  <MenuItem key={t.id} value={t.id}>{t.name}</MenuItem>
                ))}
              </Select>
            </FormControl>
            <FormControl fullWidth>
              <InputLabel>Priorität</InputLabel>
              <Select
                value={form.prioritaet || defaultPriority}
                label="Priorität"
                onChange={(e) => setForm({ ...form, prioritaet: e.target.value })}
              >
                {priorities.filter(p => p.aktiv).map(p => (
                  <MenuItem key={p.schluessel} value={p.schluessel}>{p.bezeichnung}</MenuItem>
                ))}
              </Select>
            </FormControl>
            <Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 1, mt: 1 }}>
              <Button onClick={() => navigate('/issues')}>Abbrechen</Button>
              <Button
                variant="contained"
                disabled={!form.titel.trim() || createMut.isPending}
                onClick={handleSubmit}
              >
                Erstellen
              </Button>
            </Box>
          </Box>
        </Paper>
      </Box>
    </DashboardLayout>
  );
}
