import React, { useEffect, useState } from 'react';
import { Box, Text, useInput } from 'ink';
import { useNavigation } from '../../state/navigation-context.js';
import { useInventoryCounts } from '../../hooks/useInventoryCounts.js';
import { useStorageLocations } from '../../hooks/useStorageLocations.js';
import { FormInput } from '../shared/FormInput.js';
import { LoadingSpinner } from '../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../shared/ErrorDisplay.js';

type Field = 'storageLocationId' | 'countDate';
const FIELDS: Field[] = ['storageLocationId', 'countDate'];

function todayISO(): string {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

export function InventoryCountCreateScreen() {
  const { replace, back } = useNavigation();
  const { createInventoryCount, loading, error, clearError } = useInventoryCounts();
  const { storageLocations, fetchStorageLocations } = useStorageLocations();

  const [locationIdx, setLocationIdx] = useState(0);
  const [countDate, setCountDate] = useState(todayISO());
  const [activeField, setActiveField] = useState<Field>('storageLocationId');
  const [fieldErrors, setFieldErrors] = useState<Partial<Record<Field, string>>>({});

  useEffect(() => {
    void fetchStorageLocations();
  }, [fetchStorageLocations]);

  const handleSubmit = async () => {
    const errors: Partial<Record<Field, string>> = {};
    if (storageLocations.length === 0) errors.storageLocationId = 'Kein Lagerort verfügbar.';
    if (!countDate.trim()) errors.countDate = 'Datum muss angegeben werden.';
    setFieldErrors(errors);
    if (Object.keys(errors).length > 0) return;

    const location = storageLocations[locationIdx]!;
    const result = await createInventoryCount({
      storageLocationId: location.id,
      countDate: countDate.trim(),
    });
    if (result) replace('inventory-count-detail', { inventoryCountId: result.id });
  };

  useInput((_input, key) => {
    if (loading) return;

    if (activeField === 'storageLocationId') {
      if (key.upArrow) {
        if (locationIdx > 0) setLocationIdx((i) => i - 1);
        return;
      }
      if (key.downArrow) {
        if (locationIdx < storageLocations.length - 1) setLocationIdx((i) => i + 1);
        else setActiveField('countDate');
        return;
      }
      if (key.return || key.tab) {
        setActiveField('countDate');
        return;
      }
      if (key.escape) back();
      return;
    }

    if (activeField === 'countDate') {
      if (key.escape) back();
      return;
    }
  });

  if (loading) {
    return (
      <Box flexDirection="column" alignItems="center" paddingY={2}>
        <LoadingSpinner label="Inventur wird angelegt..." />
      </Box>
    );
  }

  return (
    <Box flexDirection="column" gap={1}>
      <Text color="cyan" bold>Neue Inventur</Text>
      {error && <ErrorDisplay message={error} onDismiss={clearError} />}

      <Box flexDirection="column" gap={1} width={60}>
        {/* Storage location selector */}
        <Box flexDirection="column">
          <Text color={activeField === 'storageLocationId' ? 'cyan' : 'gray'}>Lagerort * (↑↓ auswählen)</Text>
          {fieldErrors.storageLocationId && <Text color="red">{fieldErrors.storageLocationId}</Text>}
          <Box flexDirection="column" borderStyle="round" borderColor={activeField === 'storageLocationId' ? 'cyan' : 'gray'} paddingX={1}>
            {storageLocations.length === 0 ? (
              <Text color="gray" dimColor>Keine Lagerorte verfügbar.</Text>
            ) : (
              storageLocations.slice(Math.max(0, locationIdx - 3), locationIdx + 4).map((loc, i) => {
                const actualIdx = Math.max(0, locationIdx - 3) + i;
                const isSelected = actualIdx === locationIdx;
                return (
                  <Text key={loc.id} color={isSelected ? 'cyan' : 'white'}>
                    {isSelected ? '▶ ' : '  '}{loc.name}
                  </Text>
                );
              })
            )}
          </Box>
        </Box>

        {/* Count date */}
        <FormInput
          label="Datum * (YYYY-MM-DD)"
          value={countDate}
          onChange={setCountDate}
          onSubmit={() => void handleSubmit()}
          focus={activeField === 'countDate'}
          error={fieldErrors.countDate}
          placeholder="2026-03-18"
        />
      </Box>

      <Box marginTop={1}>
        <Text color="gray" dimColor>
          ↑↓/Tab Feld wechseln · Enter bestätigen/speichern · Escape Abbrechen
        </Text>
      </Box>
    </Box>
  );
}
