import React, { useCallback, useEffect, useState } from 'react';
import { Box, Text, useInput } from 'ink';
import type { SupplierDTO, QualityCertificateDTO } from '@effigenix/api-client';
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';
import { ConfirmDialog } from '../../shared/ConfirmDialog.js';
import { client } from '../../../utils/api-client.js';

type MenuAction =
  | 'toggle-status'
  | 'rate'
  | 'add-certificate'
  | 'remove-certificate'
  | 'back';

type Mode = 'menu' | 'confirm-status' | 'confirm-remove-cert';

const MENU_ITEMS: { id: MenuAction; label: (s: SupplierDTO) => string }[] = [
  { id: 'toggle-status', label: (s) => s.status === 'ACTIVE' ? '[Deaktivieren]' : '[Aktivieren]' },
  { id: 'rate', label: () => '[Bewerten]' },
  { id: 'add-certificate', label: () => '[Zertifikat hinzufügen]' },
  { id: 'remove-certificate', label: (s) => s.certificates.length > 0 ? '[Zertifikat entfernen]' : '[Zertifikat entfernen (keine vorhanden)]' },
  { id: 'back', label: () => '[Zurück]' },
];

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

function formatDate(d: string): string {
  return new Date(d).toLocaleDateString('de-DE');
}

function avgRating(r: SupplierDTO['rating']): string {
  if (!r) return '–';
  return ((r.qualityScore + r.deliveryScore + r.priceScore) / 3).toFixed(1);
}

export function SupplierDetailScreen() {
  const { params, navigate, back } = useNavigation();
  const supplierId = params['supplierId'] ?? '';
  const { activateSupplier, deactivateSupplier, removeCertificate } = useSuppliers();

  const [supplier, setSupplier] = useState<SupplierDTO | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedAction, setSelectedAction] = useState(0);
  const [mode, setMode] = useState<Mode>('menu');
  const [actionLoading, setActionLoading] = useState(false);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [selectedCertIndex, setSelectedCertIndex] = useState(0);

  const loadSupplier = useCallback(() => {
    setLoading(true);
    setError(null);
    client.suppliers.getById(supplierId)
      .then((s) => { setSupplier(s); setLoading(false); })
      .catch((err: unknown) => { setError(errorMessage(err)); setLoading(false); });
  }, [supplierId]);

  useEffect(() => { if (supplierId) loadSupplier(); }, [loadSupplier, supplierId]);

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

    if (mode === 'confirm-remove-cert' && supplier) {
      if (key.upArrow) setSelectedCertIndex((i) => Math.max(0, i - 1));
      if (key.downArrow) setSelectedCertIndex((i) => Math.min(supplier.certificates.length - 1, i + 1));
      if (key.return) {
        const c = supplier.certificates[selectedCertIndex];
        if (c) void handleRemoveCert(c);
      }
      if (key.escape) setMode('menu');
      return;
    }

    if (mode !== 'menu') return;
    if (key.upArrow) setSelectedAction((i) => Math.max(0, i - 1));
    if (key.downArrow) setSelectedAction((i) => Math.min(MENU_ITEMS.length - 1, i + 1));
    if (key.return) void handleAction();
    if (key.backspace || key.escape) back();
  });

  const handleAction = async () => {
    if (!supplier) return;
    const item = MENU_ITEMS[selectedAction];
    if (!item) return;

    switch (item.id) {
      case 'toggle-status':
        setMode('confirm-status');
        break;
      case 'rate':
        navigate('supplier-rate', { supplierId: supplier.id });
        break;
      case 'add-certificate':
        navigate('supplier-add-certificate', { supplierId: supplier.id });
        break;
      case 'remove-certificate':
        if (supplier.certificates.length > 0) {
          setSelectedCertIndex(0);
          setMode('confirm-remove-cert');
        }
        break;
      case 'back':
        back();
        break;
    }
  };

  const handleToggleStatus = useCallback(async () => {
    if (!supplier) return;
    setMode('menu');
    setActionLoading(true);
    const fn = supplier.status === 'ACTIVE' ? deactivateSupplier : activateSupplier;
    const updated = await fn(supplier.id);
    setActionLoading(false);
    if (updated) {
      setSupplier(updated);
      setSuccessMessage(supplier.status === 'ACTIVE' ? 'Lieferant deaktiviert.' : 'Lieferant aktiviert.');
    }
  }, [supplier, activateSupplier, deactivateSupplier]);

  const handleRemoveCert = useCallback(async (cert: QualityCertificateDTO) => {
    if (!supplier) return;
    setMode('menu');
    setActionLoading(true);
    const updated = await removeCertificate(supplier.id, {
      certificateType: cert.certificateType,
      issuer: cert.issuer,
      validFrom: cert.validFrom,
    });
    setActionLoading(false);
    if (updated) {
      setSupplier(updated);
      setSuccessMessage(`Zertifikat "${cert.certificateType}" entfernt.`);
    }
  }, [supplier, removeCertificate]);

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

  const statusColor = supplier.status === 'ACTIVE' ? 'green' : 'red';

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

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

      {/* Info-Box */}
      <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={2} paddingY={1}>
        <Box gap={2}>
          <Text color="gray">Status:</Text>
          <Text color={statusColor} bold>{supplier.status}</Text>
        </Box>
        <Box gap={2}>
          <Text color="gray">Telefon:</Text>
          <Text>{supplier.contactInfo.phone}</Text>
        </Box>
        {supplier.contactInfo.email && (
          <Box gap={2}>
            <Text color="gray">E-Mail:</Text>
            <Text>{supplier.contactInfo.email}</Text>
          </Box>
        )}
        {supplier.contactInfo.contactPerson && (
          <Box gap={2}>
            <Text color="gray">Ansprechpartner:</Text>
            <Text>{supplier.contactInfo.contactPerson}</Text>
          </Box>
        )}
        {supplier.address && (
          <Box gap={2}>
            <Text color="gray">Adresse:</Text>
            <Text>{`${supplier.address.street} ${supplier.address.houseNumber}, ${supplier.address.postalCode} ${supplier.address.city}, ${supplier.address.country}`}</Text>
          </Box>
        )}
        {supplier.paymentTerms && (
          <Box gap={2}>
            <Text color="gray">Zahlungsziel:</Text>
            <Text>{supplier.paymentTerms.paymentDueDays} Tage</Text>
          </Box>
        )}
        {supplier.rating && (
          <Box gap={2}>
            <Text color="gray">Bewertung:</Text>
            <Text>
              {'★ ' + avgRating(supplier.rating)}
              {` (Q:${supplier.rating.qualityScore} L:${supplier.rating.deliveryScore} P:${supplier.rating.priceScore})`}
            </Text>
          </Box>
        )}
        {supplier.certificates.length > 0 && (
          <Box flexDirection="column" marginTop={1}>
            <Text color="gray">Zertifikate:</Text>
            {supplier.certificates.map((c) => (
              <Box key={`${c.certificateType}-${c.validFrom}`} paddingLeft={2} gap={1}>
                <Text color="yellow">•</Text>
                <Text>{c.certificateType}</Text>
                <Text color="gray">({c.issuer}, bis {formatDate(c.validUntil)})</Text>
              </Box>
            ))}
          </Box>
        )}
      </Box>

      {/* Confirm Status Dialog */}
      {mode === 'confirm-status' && (
        <ConfirmDialog
          message={supplier.status === 'ACTIVE' ? 'Lieferant deaktivieren?' : 'Lieferant aktivieren?'}
          onConfirm={() => void handleToggleStatus()}
          onCancel={() => setMode('menu')}
        />
      )}

      {/* Confirm Remove Certificate */}
      {mode === 'confirm-remove-cert' && supplier.certificates.length > 0 && (
        <Box flexDirection="column" gap={1}>
          <Text color="yellow">Zertifikat auswählen:</Text>
          {supplier.certificates.map((c, i) => (
            <Box key={`${c.certificateType}-${c.validFrom}`}>
              <Text color={i === selectedCertIndex ? 'cyan' : 'white'}>
                {i === selectedCertIndex ? '▶ ' : '  '}{c.certificateType} – {c.issuer}
              </Text>
            </Box>
          ))}
          <Text color="gray" dimColor>↑↓ auswählen · Enter Entfernen · Escape Abbrechen</Text>
        </Box>
      )}

      {/* Action Menu */}
      {mode === 'menu' && (
        <Box flexDirection="column">
          <Text color="gray" bold>Aktionen:</Text>
          {actionLoading && <LoadingSpinner label="Aktion wird ausgeführt..." />}
          {!actionLoading && MENU_ITEMS.map((item, index) => (
            <Box key={item.id}>
              <Text color={index === selectedAction ? 'cyan' : 'white'}>
                {index === selectedAction ? '▶ ' : '  '}{item.label(supplier)}
              </Text>
            </Box>
          ))}
        </Box>
      )}

      <Box marginTop={1}>
        <Text color="gray" dimColor>↑↓ navigieren · Enter ausführen · Backspace Zurück</Text>
      </Box>
    </Box>
  );
}
