'use client';

import { useState, useCallback, useEffect, useRef } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useRouter, useParams } from 'next/navigation';
import { useTranslation } from 'react-i18next';
import { apiClient } from '@/infrastructure/api/api-client';
import { queryKeys } from '@/infrastructure/api/query-keys';
import { cn } from '@/lib/utils';

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

interface SessionDetail {
  id: string;
  status: 'active' | 'completed' | 'failed';
  engineType: 'claude_code_cli' | 'claude_api';
  startedAt: string;
  endedAt?: string;
  tokenCount: number;
  totalCostUsd: number;
  taskDescription?: string;
  serverTargets?: string[];
}

interface SessionEvent {
  id: string;
  sessionId: string;
  type: 'assistant' | 'tool_use' | 'tool_result' | 'result' | 'error';
  timestamp: string;
  content: string;
}

type SessionEventsResponse = SessionEvent[];

interface SessionTask {
  id: string;
  description: string;
  status: 'pending' | 'running' | 'completed' | 'failed';
  createdAt: string;
}

type SessionTasksResponse = SessionTask[];

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const STATUS_STYLES: Record<SessionDetail['status'], string> = {
  active: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
  completed: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
  failed: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
};

const ENGINE_STYLES: Record<SessionDetail['engineType'], string> = {
  claude_code_cli: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400',
  claude_api: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
};

const EVENT_TYPE_STYLES: Record<SessionEvent['type'], string> = {
  assistant: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
  tool_use: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400',
  tool_result: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
  result: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-400',
  error: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
};

const TASK_STATUS_STYLES: Record<SessionTask['status'], string> = {
  pending: 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300',
  running: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
  completed: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
  failed: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
};

// ---------------------------------------------------------------------------
// Badge components
// ---------------------------------------------------------------------------

function StatusBadge({ status }: { status: SessionDetail['status'] }) {
  return (
    <span
      className={cn(
        'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium capitalize',
        STATUS_STYLES[status],
      )}
    >
      {status}
    </span>
  );
}

function EngineBadge({ engine }: { engine: SessionDetail['engineType'] }) {
  const { t } = useTranslation('sessions');
  const ENGINE_LABELS: Record<SessionDetail['engineType'], string> = {
    claude_code_cli: t('detail.engines.claudeCli'),
    claude_api: t('detail.engines.claudeApi'),
  };

  return (
    <span
      className={cn(
        'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium',
        ENGINE_STYLES[engine],
      )}
    >
      {ENGINE_LABELS[engine]}
    </span>
  );
}

function EventTypeBadge({ type }: { type: SessionEvent['type'] }) {
  return (
    <span
      className={cn(
        'inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium',
        EVENT_TYPE_STYLES[type],
      )}
    >
      {type.replace('_', ' ')}
    </span>
  );
}

function TaskStatusBadge({ status }: { status: SessionTask['status'] }) {
  return (
    <span
      className={cn(
        'inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium capitalize',
        TASK_STATUS_STYLES[status],
      )}
    >
      {status}
    </span>
  );
}

// ---------------------------------------------------------------------------
// Toggle switch
// ---------------------------------------------------------------------------

function ToggleSwitch({
  checked,
  disabled,
  onChange,
  label,
}: {
  checked: boolean;
  disabled?: boolean;
  onChange: (value: boolean) => void;
  label: string;
}) {
  return (
    <button
      type="button"
      onClick={() => onChange(!checked)}
      disabled={disabled}
      className="flex items-center gap-2"
      title={label}
    >
      <span
        className={cn(
          'relative inline-flex h-5 w-9 items-center rounded-full transition-colors',
          checked ? 'bg-primary' : 'bg-muted',
          disabled && 'opacity-50 cursor-not-allowed',
        )}
      >
        <span
          className={cn(
            'inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform',
            checked ? 'translate-x-[18px]' : 'translate-x-[3px]',
          )}
        />
      </span>
      <span className="text-sm">{label}</span>
    </button>
  );
}

// ---------------------------------------------------------------------------
// Helper: format date / duration
// ---------------------------------------------------------------------------

function formatDate(dateStr: string): string {
  try {
    return new Date(dateStr).toLocaleString();
  } catch {
    return dateStr;
  }
}

function formatTime(dateStr: string): string {
  try {
    return new Date(dateStr).toLocaleTimeString();
  } catch {
    return dateStr;
  }
}

function formatDuration(startStr: string, endStr?: string): string {
  const start = new Date(startStr).getTime();
  const end = endStr ? new Date(endStr).getTime() : Date.now();
  const ms = end - start;
  if (ms < 1000) return `${ms}ms`;
  const seconds = Math.floor(ms / 1000);
  if (seconds < 60) return `${seconds}s`;
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  if (minutes < 60) return `${minutes}m ${remainingSeconds}s`;
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  return `${hours}h ${remainingMinutes}m`;
}

function formatCurrency(value: number): string {
  return `$${value.toFixed(4)}`;
}

// ---------------------------------------------------------------------------
// Info row component
// ---------------------------------------------------------------------------

function InfoRow({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="flex flex-col sm:flex-row sm:items-start gap-1 sm:gap-4 py-2">
      <dt className="text-sm text-muted-foreground sm:w-36 shrink-0">{label}</dt>
      <dd className="text-sm font-medium">{value || '--'}</dd>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Main page component
// ---------------------------------------------------------------------------

export default function SessionDetailPage() {
  const { t } = useTranslation('sessions');
  const { t: tc } = useTranslation('common');
  const router = useRouter();
  const params = useParams();
  const queryClient = useQueryClient();
  const id = params.id as string;

  // State ----------------------------------------------------------------
  const [autoScroll, setAutoScroll] = useState(true);
  const [expandedEventId, setExpandedEventId] = useState<string | null>(null);
  const eventsEndRef = useRef<HTMLDivElement>(null);

  // Queries --------------------------------------------------------------
  const {
    data: session,
    isLoading,
    error,
  } = useQuery({
    queryKey: queryKeys.sessions.detail(id),
    queryFn: () => apiClient<SessionDetail>(`/api/v1/agent/sessions/${id}`),
    enabled: !!id,
  });

  const { data: eventsData } = useQuery({
    queryKey: queryKeys.sessions.events(id),
    queryFn: () =>
      apiClient<SessionEventsResponse>(
        `/api/v1/agent/sessions/${id}/events`,
      ),
    enabled: !!id,
    refetchInterval: session?.status === 'active' ? 3000 : false,
  });

  const { data: tasksData } = useQuery({
    queryKey: [...queryKeys.sessions.detail(id), 'tasks'],
    queryFn: () =>
      apiClient<SessionTasksResponse>(
        `/api/v1/agent/sessions/${id}/tasks`,
      ),
    enabled: !!id,
  });

  const events = Array.isArray(eventsData) ? eventsData : [];
  const tasks = Array.isArray(tasksData) ? tasksData : [];

  // Auto-scroll to bottom when new events arrive
  useEffect(() => {
    if (autoScroll && eventsEndRef.current) {
      eventsEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [events.length, autoScroll]);

  // Auto-refresh session if still active
  useQuery({
    queryKey: [...queryKeys.sessions.detail(id), 'poll'],
    queryFn: () => apiClient<SessionDetail>(`/api/v1/agent/sessions/${id}`),
    enabled: !!id && session?.status === 'active',
    refetchInterval: 5000,
  });

  // Render ---------------------------------------------------------------

  // Loading state
  if (isLoading) {
    return (
      <div>
        <button
          onClick={() => router.push('/audit/replay')}
          className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-1 mb-4"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M19 12H5" />
            <path d="m12 19-7-7 7-7" />
          </svg>
          {t('detail.backToSessions')}
        </button>
        <div className="text-sm text-muted-foreground py-12 text-center">
          {t('detail.loading')}
        </div>
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div>
        <button
          onClick={() => router.push('/audit/replay')}
          className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-1 mb-4"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M19 12H5" />
            <path d="m12 19-7-7 7-7" />
          </svg>
          {t('detail.backToSessions')}
        </button>
        <div className="p-4 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-sm">
          {t('detail.loadError')} {(error as Error).message}
        </div>
      </div>
    );
  }

  if (!session) return null;

  return (
    <div>
      {/* Back link */}
      <button
        onClick={() => router.push('/audit/replay')}
        className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-1 mb-4"
      >
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="16"
          height="16"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
        >
          <path d="M19 12H5" />
          <path d="m12 19-7-7 7-7" />
        </svg>
        {t('detail.backToSessions')}
      </button>

      {/* Page header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div className="flex items-center gap-3">
          <h1 className="text-2xl font-bold">{t('detail.title')}</h1>
          <StatusBadge status={session.status} />
          <EngineBadge engine={session.engineType} />
        </div>
        <code className="text-xs font-mono text-muted-foreground bg-muted px-2 py-1 rounded">
          {session.id}
        </code>
      </div>

      {/* Two-column layout */}
      <div className="grid gap-6 lg:grid-cols-3">
        {/* Left column */}
        <div className="lg:col-span-2 space-y-6">
          {/* Session Information Card */}
          <div className="bg-card border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('detail.sessionInformation')}</h2>
            <dl className="divide-y">
              <InfoRow
                label={t('detail.info.sessionId')}
                value={
                  <code className="font-mono text-xs">{session.id}</code>
                }
              />
              <InfoRow
                label={t('detail.info.status')}
                value={<StatusBadge status={session.status} />}
              />
              <InfoRow
                label={t('detail.info.engine')}
                value={<EngineBadge engine={session.engineType} />}
              />
              <InfoRow label={t('detail.info.startedAt')} value={formatDate(session.startedAt)} />
              <InfoRow
                label={t('detail.info.endedAt')}
                value={session.endedAt ? formatDate(session.endedAt) : t('detail.inProgressDuration')}
              />
              <InfoRow
                label={t('detail.info.duration')}
                value={formatDuration(session.startedAt, session.endedAt)}
              />
              <InfoRow
                label={t('detail.info.tokenCount')}
                value={
                  <span className="tabular-nums">
                    {session.tokenCount.toLocaleString()}
                  </span>
                }
              />
              <InfoRow
                label={t('detail.info.totalCost')}
                value={
                  <span className="tabular-nums">
                    {formatCurrency(session.totalCostUsd)}
                  </span>
                }
              />
              {session.taskDescription && (
                <InfoRow label={t('detail.info.task')} value={session.taskDescription} />
              )}
            </dl>
          </div>

          {/* Event Stream (Timeline) */}
          <div className="bg-card border rounded-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold">
                {t('detail.eventStream')}
                <span className="text-sm font-normal text-muted-foreground ml-2">
                  ({events.length} events)
                </span>
              </h2>
              <ToggleSwitch
                checked={autoScroll}
                onChange={setAutoScroll}
                label={t('detail.autoScroll')}
              />
            </div>

            {events.length === 0 ? (
              <p className="text-sm text-muted-foreground py-8 text-center">
                {t('detail.noEvents')}
              </p>
            ) : (
              <div className="max-h-[600px] overflow-y-auto space-y-1">
                {events.map((event) => (
                  <div
                    key={event.id}
                    className={cn(
                      'border rounded-md transition-colors',
                      expandedEventId === event.id
                        ? 'bg-muted/30 border-border'
                        : 'border-transparent hover:bg-muted/20',
                    )}
                  >
                    {/* Event header row */}
                    <button
                      onClick={() =>
                        setExpandedEventId(
                          expandedEventId === event.id ? null : event.id,
                        )
                      }
                      className="w-full flex items-center gap-3 px-3 py-2 text-left"
                    >
                      <span
                        className={cn(
                          'inline-block transition-transform text-xs text-muted-foreground',
                          expandedEventId === event.id && 'rotate-90',
                        )}
                      >
                        &#9654;
                      </span>
                      <span className="text-xs text-muted-foreground font-mono shrink-0">
                        {formatTime(event.timestamp)}
                      </span>
                      <EventTypeBadge type={event.type} />
                      <span className="text-sm truncate text-muted-foreground flex-1">
                        {event.content.substring(0, 120)}
                        {event.content.length > 120 ? '...' : ''}
                      </span>
                    </button>

                    {/* Expanded content */}
                    {expandedEventId === event.id && (
                      <div className="px-3 pb-3 pl-10">
                        <div className="bg-gray-950 text-gray-200 font-mono text-xs p-3 rounded-md whitespace-pre-wrap max-h-[400px] overflow-y-auto">
                          {event.content}
                        </div>
                      </div>
                    )}
                  </div>
                ))}
                <div ref={eventsEndRef} />
              </div>
            )}

            {session.status === 'active' && (
              <div className="mt-3 flex items-center gap-2 text-sm text-muted-foreground">
                <span className="relative flex h-2 w-2">
                  <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75" />
                  <span className="relative inline-flex rounded-full h-2 w-2 bg-blue-500" />
                </span>
                {t('detail.liveStreaming')}
              </div>
            )}
          </div>
        </div>

        {/* Right column */}
        <div className="space-y-6">
          {/* Session Stats */}
          <div className="bg-card border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('detail.statistics')}</h2>
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.info.status')}</span>
                <StatusBadge status={session.status} />
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.info.engine')}</span>
                <EngineBadge engine={session.engineType} />
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.info.duration')}</span>
                <span className="text-sm font-medium tabular-nums">
                  {formatDuration(session.startedAt, session.endedAt)}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.info.tokenCount')}</span>
                <span className="text-sm font-medium tabular-nums">
                  {session.tokenCount.toLocaleString()}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.info.totalCost')}</span>
                <span className="text-sm font-medium tabular-nums">
                  {formatCurrency(session.totalCostUsd)}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.eventStream')}</span>
                <span className="text-sm font-medium tabular-nums">
                  {events.length}
                </span>
              </div>
            </div>
          </div>

          {/* Tasks */}
          <div className="bg-card border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('detail.tasks')}</h2>
            {tasks.length === 0 ? (
              <p className="text-sm text-muted-foreground text-center py-4">
                {t('detail.noTasks')}
              </p>
            ) : (
              <div className="space-y-2">
                {tasks.map((task) => (
                  <div
                    key={task.id}
                    className="flex items-start gap-2 p-2 rounded-md border bg-muted/20"
                  >
                    <TaskStatusBadge status={task.status} />
                    <div className="flex-1 min-w-0">
                      <p className="text-sm truncate">{task.description}</p>
                      <p className="text-xs text-muted-foreground mt-0.5">
                        {formatDate(task.createdAt)}
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Server Targets */}
          {session.serverTargets && session.serverTargets.length > 0 && (
            <div className="bg-card border rounded-lg p-6">
              <h2 className="text-lg font-semibold mb-4">{t('detail.serverTargets')}</h2>
              <div className="flex flex-wrap gap-2">
                {session.serverTargets.map((server) => (
                  <span
                    key={server}
                    className="inline-flex items-center px-2.5 py-1 rounded-md bg-muted text-xs font-mono"
                  >
                    {server}
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* Timestamps */}
          <div className="bg-card border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('detail.timestamps')}</h2>
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.info.startedAt')}</span>
                <span className="text-xs text-muted-foreground">
                  {formatDate(session.startedAt)}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.info.endedAt')}</span>
                <span className="text-xs text-muted-foreground">
                  {session.endedAt ? formatDate(session.endedAt) : t('detail.inProgressStatus')}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
