import React, { useEffect, useState } from 'react';
import { Box, Text, useInput } from 'ink';
import type { ProductCategoryDTO } from '@effigenix/api-client';
import { useNavigation } from '../../../state/navigation-context.js';
import { useCategories } from '../../../hooks/useCategories.js';
import { FormInput } from '../../shared/FormInput.js';
import { LoadingSpinner } from '../../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../../shared/ErrorDisplay.js';
import { SuccessDisplay } from '../../shared/SuccessDisplay.js';
import { client } from '../../../utils/api-client.js';

type Mode = 'view' | 'edit';
type EditField = 'name' | 'description';
const EDIT_FIELDS: EditField[] = ['name', 'description'];

function errorMessage(err: unknown): string {
  return err instanceof Error ? err.message : 'Unbekannter Fehler';
}

export function CategoryDetailScreen() {
  const { params, back } = useNavigation();
  const categoryId = params['categoryId'] ?? '';
  const { updateCategory } = useCategories();

  const [category, setCategory] = useState<ProductCategoryDTO | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [mode, setMode] = useState<Mode>('view');
  const [activeField, setActiveField] = useState<EditField>('name');
  const [editName, setEditName] = useState('');
  const [editDescription, setEditDescription] = useState('');
  const [saving, setSaving] = useState(false);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  useEffect(() => {
    setLoading(true);
    client.categories.getById(categoryId)
      .then((cat) => { setCategory(cat); setLoading(false); })
      .catch((err: unknown) => { setError(errorMessage(err)); setLoading(false); });
  }, [categoryId]);

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

    if (mode === 'view') {
      if (key.return || _input === 'e') {
        if (category) {
          setEditName(category.name);
          setEditDescription(category.description ?? '');
          setActiveField('name');
          setMode('edit');
        }
      }
      if (key.backspace || key.escape) back();
    }

    if (mode === 'edit') {
      if (key.tab || key.downArrow) {
        setActiveField((f) => {
          const idx = EDIT_FIELDS.indexOf(f);
          return EDIT_FIELDS[(idx + 1) % EDIT_FIELDS.length] ?? f;
        });
      }
      if (key.upArrow) {
        setActiveField((f) => {
          const idx = EDIT_FIELDS.indexOf(f);
          return EDIT_FIELDS[(idx - 1 + EDIT_FIELDS.length) % EDIT_FIELDS.length] ?? f;
        });
      }
      if (key.escape) setMode('view');
    }
  });

  const handleSave = async () => {
    if (!category || !editName.trim()) return;
    setSaving(true);
    setError(null);
    const updated = await updateCategory(
      category.id,
      editName.trim(),
      editDescription.trim() || null,
    );
    setSaving(false);
    if (updated) {
      setCategory(updated);
      setMode('view');
      setSuccessMessage('Kategorie gespeichert.');
    }
  };

  if (loading) return <LoadingSpinner label="Lade Kategorie..." />;
  if (error && !category) return <ErrorDisplay message={error} onDismiss={back} />;
  if (!category) return <Text color="red">Kategorie nicht gefunden.</Text>;

  return (
    <Box flexDirection="column" gap={1}>
      <Text color="cyan" bold>Kategorie: {category.name}</Text>

      {error && <ErrorDisplay message={error} onDismiss={() => setError(null)} />}
      {successMessage && <SuccessDisplay message={successMessage} onDismiss={() => setSuccessMessage(null)} />}

      {mode === 'view' && (
        <>
          <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={2} paddingY={1}>
            <Box gap={2}>
              <Text color="gray">ID:</Text>
              <Text dimColor>{category.id}</Text>
            </Box>
            <Box gap={2}>
              <Text color="gray">Name:</Text>
              <Text bold>{category.name}</Text>
            </Box>
            <Box gap={2}>
              <Text color="gray">Beschreibung:</Text>
              <Text>{category.description ?? '–'}</Text>
            </Box>
          </Box>

          <Box marginTop={1}>
            <Text color="gray" dimColor>
              [e]/Enter Bearbeiten · Backspace Zurück
            </Text>
          </Box>
        </>
      )}

      {mode === 'edit' && (
        <>
          {saving && <LoadingSpinner label="Speichere..." />}
          {!saving && (
            <Box flexDirection="column" gap={1} width={60}>
              <FormInput
                label="Name *"
                value={editName}
                onChange={setEditName}
                onSubmit={() => {
                  if (activeField === 'description') void handleSave();
                  else setActiveField('description');
                }}
                focus={activeField === 'name'}
              />
              <FormInput
                label="Beschreibung"
                value={editDescription}
                onChange={setEditDescription}
                onSubmit={() => void handleSave()}
                focus={activeField === 'description'}
                placeholder="(optional)"
              />
            </Box>
          )}
          <Box marginTop={1}>
            <Text color="gray" dimColor>
              Tab/↑↓ Feld wechseln · Enter auf letztem Feld speichern · Escape Abbrechen
            </Text>
          </Box>
        </>
      )}
    </Box>
  );
}
