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

export function RoleDetailScreen() {
  const { params, back } = useNavigation();
  const roleId = params['roleId'] ?? '';

  const [role, setRole] = useState<RoleDTO | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!roleId) return;

    setLoading(true);
    setError(null);

    client.roles
      .list()
      .then((roles) => {
        const found = roles.find((r) => r.id === roleId) ?? null;
        setRole(found);
        if (!found) setError('Rolle nicht gefunden.');
      })
      .catch((err: unknown) => {
        setError(err instanceof Error ? err.message : 'Unbekannter Fehler');
      })
      .finally(() => {
        setLoading(false);
      });
  }, [roleId]);

  useInput((_input, key) => {
    if (loading) return;
    if (key.backspace || key.escape) {
      back();
    }
  });

  if (loading) {
    return <LoadingSpinner label="Lade Rollendetails..." />;
  }

  if (error) {
    return <ErrorDisplay message={error} onDismiss={() => back()} />;
  }

  if (!role) {
    return <Text color="red">Rolle nicht gefunden.</Text>;
  }

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

      {/* Role Info */}
      <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={2} paddingY={1}>
        <Box gap={2}>
          <Text color="gray">ID:</Text>
          <Text>{role.id}</Text>
        </Box>
        <Box gap={2}>
          <Text color="gray">Name:</Text>
          <Text bold>{role.name}</Text>
        </Box>
        <Box gap={2}>
          <Text color="gray">Berechtigungen:</Text>
          <Text>{role.permissions.length}</Text>
        </Box>
      </Box>

      {/* Permissions List */}
      {role.permissions.length > 0 && (
        <Box flexDirection="column" gap={0}>
          <Text color="gray" bold>
            Berechtigungen:
          </Text>
          <Box
            flexDirection="column"
            borderStyle="round"
            borderColor="gray"
            paddingX={2}
            paddingY={1}
          >
            {role.permissions.map((perm) => (
              <Box key={perm}>
                <Text color="white">• {perm}</Text>
              </Box>
            ))}
          </Box>
        </Box>
      )}

      {role.permissions.length === 0 && (
        <Text color="gray" dimColor>
          Keine Berechtigungen zugewiesen.
        </Text>
      )}

      <Box marginTop={1}>
        <Text color="gray" dimColor>
          Backspace / Escape Zurück
        </Text>
      </Box>
    </Box>
  );
}
