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

const VikunjaQuickAddWidget: React.FC = () => {
  const [title, setTitle] = useState('');
  const [projectId, setProjectId] = useState<number | ''>('');
  const [dueDate, setDueDate] = useState('');
  const { showSuccess, showError } = useNotification();
  const queryClient = useQueryClient();

  const { data: projectsData, isLoading: projectsLoading } = useQuery({
    queryKey: ['vikunja-projects'],
    queryFn: () => vikunjaApi.getProjects(),
    refetchInterval: 10 * 60 * 1000,
    retry: 1,
  });

  const configured = projectsData?.configured ?? true;
  const projects = projectsData?.data ?? [];

  const mutation = useMutation({
    mutationFn: () =>
      vikunjaApi.createTask(
        projectId as number,
        title,
        dueDate || undefined,
      ),
    onSuccess: () => {
      showSuccess('Aufgabe erstellt');
      setTitle('');
      setDueDate('');
      setProjectId('');
      queryClient.invalidateQueries({ queryKey: ['vikunja-my-tasks'] });
    },
    onError: () => {
      showError('Aufgabe konnte nicht erstellt werden');
    },
  });

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

  if (!configured) {
    return (
      <WidgetCard
        title="Aufgabe erstellen"
        icon={<AddTask />}
        isEmpty
        emptyMessage="Vikunja nicht eingerichtet"
      />
    );
  }

  if (projectsLoading) {
    return (
      <WidgetCard
        title="Aufgabe erstellen"
        icon={<AddTask />}
        isLoading
        skeleton={<FormSkeleton />}
      />
    );
  }

  return (
    <FormCard
      title="Aufgabe erstellen"
      icon={<AddTask />}
      isSubmitting={mutation.isPending}
      onSubmit={handleSubmit}
      submitLabel="Erstellen"
    >
      <FormControl fullWidth size="small">
        <InputLabel>Projekt</InputLabel>
        <Select
          value={projectId}
          label="Projekt"
          onChange={(e: SelectChangeEvent<number | ''>) =>
            setProjectId(e.target.value as number | '')
          }
        >
          {projects.map((p) => (
            <MenuItem key={p.id} value={p.id}>
              {p.title}
            </MenuItem>
          ))}
        </Select>
      </FormControl>

      <TextField
        fullWidth
        size="small"
        label="Titel"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
        inputProps={{ maxLength: 250 }}
      />

      <GermanDateField
        mode="date"
        fullWidth
        size="small"
        label="Fälligkeitsdatum (optional)"
        value={dueDate}
        onChange={(v) => setDueDate(v)}
      />
    </FormCard>
  );
};

export default VikunjaQuickAddWidget;
