import React, { useState } from 'react';
import {
  TextField,
  Switch,
  FormControlLabel,
  Typography,
} from '@mui/material';
import { CalendarMonth } from '@mui/icons-material';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { eventsApi } from '../../services/events';
import type { CreateVeranstaltungInput } from '../../types/events.types';
import { useNotification } from '../../contexts/NotificationContext';
import { usePermissionContext } from '../../contexts/PermissionContext';
import { FormCard } from '../templates/FormCard';

function toDatetimeLocal(date: Date): string {
  const pad = (n: number) => String(n).padStart(2, '0');
  return (
    date.getFullYear() +
    '-' + pad(date.getMonth() + 1) +
    '-' + pad(date.getDate()) +
    'T' + pad(date.getHours()) +
    ':' + pad(date.getMinutes())
  );
}

function toDateOnly(date: Date): string {
  const pad = (n: number) => String(n).padStart(2, '0');
  return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate());
}

function makeDefaults() {
  const now = new Date();
  const later = new Date(now.getTime() + 2 * 60 * 60 * 1000);
  return { datumVon: toDatetimeLocal(now), datumBis: toDatetimeLocal(later) };
}

const EventQuickAddWidget: React.FC = () => {
  const { hasPermission } = usePermissionContext();
  const canWrite = hasPermission('kalender:create');

  const defaults = makeDefaults();
  const [titel, setTitel] = useState('');
  const [datumVon, setDatumVon] = useState(defaults.datumVon);
  const [datumBis, setDatumBis] = useState(defaults.datumBis);
  const [ganztaegig, setGanztaegig] = useState(false);
  const [beschreibung, setBeschreibung] = useState('');

  const { showSuccess, showError } = useNotification();
  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: () => {
      let datum_von: string;
      let datum_bis: string;

      if (ganztaegig) {
        const vonDate = new Date(datumVon);
        const bisDate = new Date(datumBis);
        datum_von = new Date(toDateOnly(vonDate) + 'T00:00:00').toISOString();
        datum_bis = new Date(toDateOnly(bisDate) + 'T23:59:59').toISOString();
      } else {
        datum_von = new Date(datumVon).toISOString();
        datum_bis = new Date(datumBis).toISOString();
      }

      const data: CreateVeranstaltungInput = {
        titel: titel.trim(),
        beschreibung: beschreibung.trim() || null,
        ort: null,
        kategorie_id: null,
        datum_von,
        datum_bis,
        ganztaegig,
        zielgruppen: [],
        alle_gruppen: true,
        max_teilnehmer: null,
        anmeldung_erforderlich: false,
      };
      return eventsApi.createEvent(data);
    },
    onSuccess: () => {
      showSuccess('Veranstaltung erstellt');
      const fresh = makeDefaults();
      setTitel('');
      setDatumVon(fresh.datumVon);
      setDatumBis(fresh.datumBis);
      setGanztaegig(false);
      setBeschreibung('');
      queryClient.invalidateQueries({ queryKey: ['events'] });
      queryClient.invalidateQueries({ queryKey: ['upcoming-events'] });
    },
    onError: () => {
      showError('Veranstaltung konnte nicht erstellt werden');
    },
  });

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

  if (!canWrite) return null;

  const dateFieldType = ganztaegig ? 'date' : 'datetime-local';

  const datumVonValue = ganztaegig ? datumVon.slice(0, 10) : datumVon;
  const datumBisValue = ganztaegig ? datumBis.slice(0, 10) : datumBis;

  return (
    <FormCard
      title="Veranstaltung"
      icon={<CalendarMonth />}
      isSubmitting={mutation.isPending}
      onSubmit={handleSubmit}
      submitLabel="Erstellen"
    >
      <TextField
        fullWidth
        size="small"
        label="Titel"
        value={titel}
        onChange={(e) => setTitel(e.target.value)}
        required
        inputProps={{ maxLength: 250 }}
      />

      <FormControlLabel
        control={
          <Switch
            checked={ganztaegig}
            onChange={(e) => setGanztaegig(e.target.checked)}
            size="small"
          />
        }
        label={<Typography variant="body2">Ganztägig</Typography>}
        sx={{ mx: 0 }}
      />

      <TextField
        fullWidth
        size="small"
        label="Datum von"
        type={dateFieldType}
        value={datumVonValue}
        onChange={(e) => {
          const val = e.target.value;
          setDatumVon(ganztaegig ? val + 'T00:00' : val);
        }}
        required
        InputLabelProps={{ shrink: true }}
      />

      <TextField
        fullWidth
        size="small"
        label="Datum bis"
        type={dateFieldType}
        value={datumBisValue}
        onChange={(e) => {
          const val = e.target.value;
          setDatumBis(ganztaegig ? val + 'T00:00' : val);
        }}
        required
        InputLabelProps={{ shrink: true }}
      />

      <TextField
        fullWidth
        size="small"
        label="Beschreibung (optional)"
        value={beschreibung}
        onChange={(e) => setBeschreibung(e.target.value)}
        multiline
        rows={2}
        inputProps={{ maxLength: 1000 }}
      />
    </FormCard>
  );
};

export default EventQuickAddWidget;
