'use client';

import React from 'react';
import { Box, Text, Group, Stack, ActionIcon, Tooltip } from '@tidbcloud/uikit';
import { Source, getSourceTypeMeta, isPreparedSource, useWorkspace } from '@/lib/workspace';
import { useTranslation } from '@/lib/i18n';

interface SourceCardProps {
  source: Source;
  isSelected: boolean;
  onClick: () => void;
  /** When true, disables all interaction. */
  disabled?: boolean;
}

export default function SourceCard({ source, isSelected, onClick, disabled = false }: SourceCardProps) {
  const { t } = useTranslation();
  const { removeSource } = useWorkspace();
  const meta = getSourceTypeMeta((source as any)?.type);
  const isSkill = source.type === 'skill';
  const isLoading = source.status === 'loading';
  const isError = source.status === 'error';
  const isReady = source.status === 'ready';
  const isPrepared = isPreparedSource(source);

  const handleClick = () => {
    if (disabled || isLoading || isSkill) return;
    onClick();
  };

  const getBorderStyle = () => {
    if (isLoading) return '1px solid #93c5fd';
    if (isError) return '1px solid #fca5a5';
    if (isSkill) return '1px solid transparent';
    return isSelected ? '2px solid #3b82f6' : '1px solid transparent';
  };

  const getBackgroundStyle = () => {
    if (isLoading) return '#eff6ff';
    if (isError) return '#fef2f2';
    if (isSkill) return '#f9fafb';
    return isSelected ? '#eff6ff' : 'transparent';
  };

  const tooltipDescription = isSkill
    ? source.description
    : undefined;
  const jiraPrimaryText = source.issueId || source.name;
  const jiraSecondaryText = source.name && source.name !== source.issueId ? source.name : meta.label;
  const primaryText = isPrepared ? jiraPrimaryText : source.name;
  const secondaryText = isLoading ? (source.statusMessage || t('sources.card.loading'))
    : isError ? (source.statusMessage || t('sources.card.failed'))
    : (disabled && isSkill) ? t('sources.card.tempDisabled')
    : isPrepared ? jiraSecondaryText
    : meta.label;

  const card = (
    <Box
      py={6}
      px="sm"
      onClick={handleClick}
      style={{
        borderRadius: '6px',
        border: getBorderStyle(),
        backgroundColor: getBackgroundStyle(),
        cursor: disabled ? 'default' : (isSkill || isLoading ? 'default' : 'pointer'),
        transition: 'all 0.12s ease',
        opacity: disabled ? 0.5 : 1,
      }}
    >
      <Group gap={8} align="center" wrap="nowrap">
        {/* Left: icon */}
        <span style={{ fontSize: '18px', flexShrink: 0, lineHeight: 1 }}>{meta.icon}</span>

        {/* Center: name (primary) + badge (secondary) */}
        <Stack gap={2} style={{ flex: 1, minWidth: 0 }}>
          <Text
            size="sm"
            fw={400}
            style={{
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              color: isError ? '#ef4444' : isSkill ? '#374151' : undefined,
              lineHeight: 1.3,
              fontFamily: isSkill ? 'monospace' : undefined,
              fontSize: isSkill ? '12px' : undefined,
            }}
          >
            {primaryText}
          </Text>
          <Text
            size="xs"
            style={{
              color: isError ? '#ef4444'
                : isLoading ? '#3b82f6'
                : isPrepared ? '#dc2626'
                : (disabled && isSkill) ? '#d97706'
                : '#9ca3af',
              lineHeight: 1,
              letterSpacing: '0.02em',
              fontWeight: 500,
              textTransform: 'uppercase',
              fontSize: '10px',
              fontFamily: isPrepared && !isLoading && !isError
                  ? 'monospace'
                  : undefined,
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
          >
            {secondaryText}
          </Text>
        </Stack>

        {/* Right: status indicators + remove */}
        {isLoading && (
          <Box
            style={{
              width: '12px',
              height: '12px',
              borderRadius: '50%',
              border: '2px solid #3b82f6',
              borderTopColor: 'transparent',
              animation: 'spin 0.8s linear infinite',
              flexShrink: 0,
            }}
          />
        )}

        {isReady && (
          <Tooltip label={t('sources.card.ready')}>
            <span style={{ fontSize: '13px', lineHeight: 1, color: '#10b981', flexShrink: 0 }}>✓</span>
          </Tooltip>
        )}

        {isError && (
          <Tooltip label={source.statusMessage || t('sources.card.preparationFailed')}>
            <span style={{ fontSize: '13px', lineHeight: 1, color: '#ef4444', flexShrink: 0 }}>!</span>
          </Tooltip>
        )}

        {!source.readonly && source.type !== 'skill' && !isLoading && (
          <Tooltip label={t('sources.card.remove')}>
            <ActionIcon
              variant="subtle"
              color="gray"
              size="xs"
              onClick={(e: React.MouseEvent) => {
                e.stopPropagation();
                removeSource(source.id);
              }}
              aria-label={t('sources.card.removeAria')}
            >
              <span style={{ fontSize: '11px', lineHeight: 1 }}>✕</span>
            </ActionIcon>
          </Tooltip>
        )}
      </Group>
    </Box>
  );

  if (tooltipDescription) {
    return (
      <Tooltip
        label={tooltipDescription}
        multiline
        w={280}
        withArrow
        position="right"
        openDelay={500}
        styles={{ tooltip: { fontSize: '12px', lineHeight: 1.4, whiteSpace: 'pre-line' } }}
      >
        {card}
      </Tooltip>
    );
  }

  return card;
}
