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

type ScoreField = 'quality' | 'delivery' | 'price';
const FIELDS: ScoreField[] = ['quality', 'delivery', 'price'];

const FIELD_LABELS: Record<ScoreField, string> = {
  quality: 'Qualität',
  delivery: 'Lieferung',
  price: 'Preis',
};

function ScoreSelector({ label, value, active }: { label: string; value: number; active: boolean }) {
  return (
    <Box gap={2}>
      <Text color={active ? 'cyan' : 'gray'} bold={active}>{label.padEnd(12)}</Text>
      <Box gap={1}>
        {[1, 2, 3, 4, 5].map((n) => (
          <Text key={n} color={n <= value ? 'yellow' : 'gray'}>
            {n <= value ? '★' : '☆'}
          </Text>
        ))}
        <Text color={active ? 'cyan' : 'gray'}> {value}/5</Text>
      </Box>
    </Box>
  );
}

export function RateSupplierScreen() {
  const { params, replace, back } = useNavigation();
  const supplierId = params['supplierId'] ?? '';
  const { rateSupplier, loading, error, clearError } = useSuppliers();

  const [scores, setScores] = useState<Record<ScoreField, number>>({ quality: 3, delivery: 3, price: 3 });
  const [activeField, setActiveField] = useState<ScoreField>('quality');
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

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

    if (key.upArrow) {
      setActiveField((f) => {
        const idx = FIELDS.indexOf(f);
        return FIELDS[Math.max(0, idx - 1)] ?? f;
      });
    }
    if (key.downArrow) {
      setActiveField((f) => {
        const idx = FIELDS.indexOf(f);
        return FIELDS[Math.min(FIELDS.length - 1, idx + 1)] ?? f;
      });
    }
    if (key.leftArrow) {
      setScores((s) => ({ ...s, [activeField]: Math.max(1, s[activeField] - 1) }));
    }
    if (key.rightArrow) {
      setScores((s) => ({ ...s, [activeField]: Math.min(5, s[activeField] + 1) }));
    }
    if (key.return && activeField === 'price') {
      void handleSubmit();
    }
    if (key.return && activeField !== 'price') {
      setActiveField((f) => {
        const idx = FIELDS.indexOf(f);
        return FIELDS[idx + 1] ?? f;
      });
    }
    if (key.escape) back();
  });

  const handleSubmit = async () => {
    const updated = await rateSupplier(supplierId, {
      qualityScore: scores.quality,
      deliveryScore: scores.delivery,
      priceScore: scores.price,
    });
    if (updated) {
      setSuccessMessage('Bewertung gespeichert.');
      setTimeout(() => replace('supplier-detail', { supplierId }), 1000);
    }
  };

  if (loading) return <LoadingSpinner label="Bewertung wird gespeichert..." />;

  return (
    <Box flexDirection="column" gap={1}>
      <Text color="cyan" bold>Lieferant bewerten</Text>

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

      <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={2} paddingY={1} gap={1}>
        {FIELDS.map((field) => (
          <ScoreSelector
            key={field}
            label={FIELD_LABELS[field]}
            value={scores[field]}
            active={activeField === field}
          />
        ))}
      </Box>

      <Box marginTop={1}>
        <Text color="gray" dimColor>
          ↑↓ Kriterium · ←→ Bewertung ändern · Enter nächstes/Speichern · Escape Abbrechen
        </Text>
      </Box>
    </Box>
  );
}
