import React, { useState } from 'react';
import {
  TextField,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  SelectChangeEvent,
} from '@mui/material';
import { DirectionsCar } from '@mui/icons-material';
import GermanDateField from '../shared/GermanDateField';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { bookingApi, fetchVehicles } from '../../services/bookings';
import type { CreateBuchungInput } from '../../types/booking.types';
import { useNotification } from '../../contexts/NotificationContext';
import { FormCard } from '../templates/FormCard';
import { WidgetCard } from '../templates/WidgetCard';
import { FormSkeleton } from '../templates/SkeletonPresets';

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 makeDefaults() {
  const now = new Date();
  const later = new Date(now.getTime() + 2 * 60 * 60 * 1000);
  return { beginn: toDatetimeLocal(now), ende: toDatetimeLocal(later) };
}

const VehicleBookingQuickAddWidget: React.FC = () => {
  const defaults = makeDefaults();
  const [fahrzeugId, setFahrzeugId] = useState<string>('');
  const [titel, setTitel] = useState('');
  const [beginn, setBeginn] = useState(defaults.beginn);
  const [ende, setEnde] = useState(defaults.ende);
  const [beschreibung, setBeschreibung] = useState('');

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

  const { data: vehicles, isLoading: vehiclesLoading } = useQuery({
    queryKey: ['vehicles'],
    queryFn: fetchVehicles,
    refetchInterval: 10 * 60 * 1000,
    retry: 1,
  });

  const mutation = useMutation({
    mutationFn: () => {
      const beginnDate = new Date(beginn);
      const endeDate = new Date(ende);
      if (isNaN(beginnDate.getTime()) || isNaN(endeDate.getTime())) {
        return Promise.reject(new Error('Ungültiges Datum'));
      }
      const data: CreateBuchungInput = {
        fahrzeugId,
        titel: titel.trim(),
        beschreibung: beschreibung.trim() || null,
        beginn: beginnDate.toISOString(),
        ende: endeDate.toISOString(),
        buchungsArt: 'intern',
      };
      return bookingApi.create(data);
    },
    onSuccess: () => {
      showSuccess('Fahrzeugbuchung erstellt');
      const fresh = makeDefaults();
      setFahrzeugId('');
      setTitel('');
      setBeginn(fresh.beginn);
      setEnde(fresh.ende);
      setBeschreibung('');
      queryClient.invalidateQueries({ queryKey: ['bookings'] });
      queryClient.invalidateQueries({ queryKey: ['upcoming-vehicle-bookings'] });
    },
    onError: () => {
      showError('Fahrzeugbuchung konnte nicht erstellt werden');
    },
  });

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

  if (vehiclesLoading) {
    return (
      <WidgetCard
        title="Fahrzeugbuchung"
        icon={<DirectionsCar />}
        isLoading
        skeleton={<FormSkeleton />}
      />
    );
  }

  return (
    <FormCard
      title="Fahrzeugbuchung"
      icon={<DirectionsCar />}
      isSubmitting={mutation.isPending}
      onSubmit={handleSubmit}
      submitLabel="Erstellen"
    >
      <FormControl fullWidth size="small">
        <InputLabel>Fahrzeug</InputLabel>
        <Select
          value={fahrzeugId}
          label="Fahrzeug"
          onChange={(e: SelectChangeEvent<string>) => setFahrzeugId(e.target.value)}
        >
          {(vehicles ?? []).map((v) => (
            <MenuItem key={v.id} value={v.id}>
              {v.bezeichnung}
            </MenuItem>
          ))}
        </Select>
      </FormControl>

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

      <GermanDateField
        mode="datetime"
        fullWidth
        size="small"
        label="Beginn"
        value={beginn}
        onChange={(v) => setBeginn(v)}
        required
      />

      <GermanDateField
        mode="datetime"
        fullWidth
        size="small"
        label="Ende"
        value={ende}
        onChange={(v) => setEnde(v)}
        required
      />

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

export default VehicleBookingQuickAddWidget;
