'use client';

import { useLocale } from '@tale/ui/i18n/locale-provider';
import { type StatGridItem, StatGrid } from '@tale/ui/stat-grid';
import { Text } from '@tale/ui/text';
import { useMemo } from 'react';

import { ViewDialog } from '@/app/components/ui/dialog/view-dialog';
import { Field, FieldGroup } from '@/app/components/ui/forms/field';
import { useT } from '@/lib/i18n/client';
import { formatNumber } from '@/lib/utils/format/number';

import type { ToolUsage } from '../hooks/queries';

function formatToolName(toolName: string): string {
  const nameMap: Record<string, string> = {
    crm_assistant: 'CRM',
    integration_assistant: 'Integration',
    workflow_assistant: 'Workflow',
  };
  return nameMap[toolName] ?? toolName;
}

interface ToolDetailsDialogProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  usage: ToolUsage | null;
}

export function ToolDetailsDialog({
  isOpen,
  onOpenChange,
  usage,
}: ToolDetailsDialogProps) {
  const { locale } = useLocale();
  const { t } = useT('chat');

  const tokenItems = useMemo<StatGridItem[]>(
    () => [
      ...(usage?.inputTokens !== undefined
        ? [
            {
              label: t('messageInfo.input'),
              value: (
                <Text variant="label">
                  {formatNumber(usage.inputTokens, locale)}
                </Text>
              ),
            },
          ]
        : []),
      ...(usage?.outputTokens !== undefined
        ? [
            {
              label: t('messageInfo.output'),
              value: (
                <Text variant="label">
                  {formatNumber(usage.outputTokens, locale)}
                </Text>
              ),
            },
          ]
        : []),
      ...(usage?.totalTokens !== undefined
        ? [
            {
              label: t('messageInfo.total'),
              value: (
                <Text variant="label">
                  {formatNumber(usage.totalTokens, locale)}
                </Text>
              ),
            },
          ]
        : []),
      ...(usage?.durationMs !== undefined
        ? [
            {
              label: t('messageInfo.duration'),
              value: (
                <Text variant="label">
                  {(usage.durationMs / 1000).toFixed(2)}s
                </Text>
              ),
            },
          ]
        : []),
    ],
    [usage, t, locale],
  );

  if (!usage) return null;

  const toolDisplayName = formatToolName(usage.toolName);

  return (
    <ViewDialog
      open={isOpen}
      onOpenChange={onOpenChange}
      title={t('toolDetails.title', { tool: toolDisplayName })}
      className="overflow-x-hidden sm:max-w-[600px]"
    >
      <FieldGroup gap={4}>
        {usage.model && (
          <Field label={t('messageInfo.model')}>
            <Text as="div">
              {usage.model}
              {usage.provider && ` (${usage.provider})`}
            </Text>
          </Field>
        )}

        {tokenItems.length > 0 && (
          <Field label={t('messageInfo.tokenUsage')}>
            <StatGrid items={tokenItems} />
          </Field>
        )}

        {usage.input && (
          <Field label={t('toolDetails.input')}>
            <div className="bg-muted max-h-40 overflow-y-auto rounded px-3 py-2 text-sm break-all">
              {usage.input}
            </div>
          </Field>
        )}

        {usage.output && (
          <Field label={t('toolDetails.output')}>
            <div className="bg-muted max-h-60 overflow-y-auto rounded px-3 py-2 text-sm break-all">
              {usage.output}
            </div>
          </Field>
        )}
      </FieldGroup>
    </ViewDialog>
  );
}
