import { Link } from "@tanstack/react-router";
import { ChevronLeft } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { QuestionForm } from "@/components/QuestionForm";
import { AgentOutputViewer } from "@/components/AgentOutputViewer";
import { formatRelativeTime } from "@/lib/utils";
import { trpc } from "@/lib/trpc";

function processDescription(content: string | null): string | null {
  if (!content) return null;
  const stripped = content.replace(/<[^>]*>/g, '');
  return stripped.length > 300 ? stripped.slice(0, 300) + '…' : stripped;
}

interface InboxDetailPanelProps {
  agent: {
    id: string;
    name: string;
    status: string;
    taskId: string | null;
    taskName: string | null;
    phaseName: string | null;
    initiativeName: string | null;
    initiativeId: string | null;
    updatedAt: string;
  };
  taskDescription: string | null;
  isLoadingContext: boolean;
  message: {
    id: string;
    content: string;
    requiresResponse: boolean;
  } | null;
  questions:
    | {
        id: string;
        question: string;
        options: any;
        multiSelect: boolean;
      }[]
    | null;
  isLoadingQuestions: boolean;
  questionsError: string | null;
  onBack: () => void;
  onSubmitAnswers: (answers: Record<string, string>) => void;
  onDismissQuestions: () => void;
  onDismissMessage: () => void;
  isSubmitting: boolean;
  isDismissingQuestions: boolean;
  isDismissingMessage: boolean;
  submitError: string | null;
  dismissMessageError: string | null;
}

export function InboxDetailPanel({
  agent,
  taskDescription,
  isLoadingContext,
  message,
  questions,
  isLoadingQuestions,
  questionsError,
  onBack,
  onSubmitAnswers,
  onDismissQuestions,
  onDismissMessage,
  isSubmitting,
  isDismissingQuestions,
  isDismissingMessage,
  submitError,
  dismissMessageError,
}: InboxDetailPanelProps) {
  const [logsOpen, setLogsOpen] = useState(false);
  const logsContainerRef = useRef<HTMLDivElement>(null);
  const outputQuery = trpc.getAgentOutput.useQuery({ id: agent.id });

  useEffect(() => {
    setLogsOpen(false);
  }, [agent.id]);

  useEffect(() => {
    if (logsOpen && logsContainerRef.current) {
      logsContainerRef.current.scrollTop = logsContainerRef.current.scrollHeight;
    }
  }, [logsOpen]);

  const processedDescription = processDescription(taskDescription);

  return (
    <div className="space-y-4 rounded-lg border border-border p-4">
      {/* Mobile back button */}
      <Button
        variant="ghost"
        size="sm"
        className="lg:hidden"
        onClick={onBack}
      >
        <ChevronLeft className="mr-1 h-4 w-4" />
        Back to list
      </Button>

      {/* Detail Header */}
      <div className="border-b border-border pb-3">
        <div className="flex items-center justify-between">
          <h3 className="text-sm font-bold">
            {agent.name}{" "}
            <span className="font-normal text-muted-foreground">
              &rarr; You
            </span>
          </h3>
          <span className="text-xs text-muted-foreground">
            {formatRelativeTime(agent.updatedAt)}
          </span>
        </div>
        <p className="mt-1 text-xs text-muted-foreground">
          Task:{" "}
          {agent.taskName ?? agent.taskId ?? "—"}
        </p>
        {agent.taskId && (
          <Link
            to="/initiatives"
            className="mt-1 inline-block text-xs text-primary hover:underline"
          >
            View in context &rarr;
          </Link>
        )}
      </div>

      {/* Related Context Panel */}
      {isLoadingContext ? (
        <div className="space-y-2 py-2">
          <Skeleton className="h-3 w-40" />
          <Skeleton className="h-3 w-56" />
          <Skeleton className="h-3 w-48" />
        </div>
      ) : agent.taskId ? (
        <div className="space-y-1 rounded-md bg-muted/40 p-3 text-xs text-muted-foreground">
          {agent.initiativeName && agent.initiativeId && (
            <p>
              Initiative:{" "}
              <Link
                to="/initiatives/$initiativeId"
                params={{ initiativeId: agent.initiativeId }}
                className="text-primary hover:underline"
              >
                {agent.initiativeName}
              </Link>
            </p>
          )}
          {agent.taskName && (
            <p>Task: <span className="text-foreground">{agent.taskName}</span></p>
          )}
          {processedDescription && (
            <p className="text-muted-foreground">{processedDescription}</p>
          )}
          {agent.phaseName && <p>Phase: {agent.phaseName}</p>}
        </div>
      ) : (
        <p className="text-xs text-muted-foreground">No task context available</p>
      )}

      {/* Question Form or Notification Content */}
      {isLoadingQuestions && (
        <div className="py-4 text-center text-sm text-muted-foreground">
          Loading questions...
        </div>
      )}

      {questionsError && (
        <div className="py-4 text-center text-sm text-destructive">
          Failed to load questions: {questionsError}
        </div>
      )}

      {questions && questions.length > 0 && (
        <QuestionForm
          questions={questions}
          onSubmit={onSubmitAnswers}
          onCancel={onBack}
          onDismiss={onDismissQuestions}
          isSubmitting={isSubmitting}
          isDismissing={isDismissingQuestions}
        />
      )}

      {submitError && (
        <p className="text-sm text-destructive">Error: {submitError}</p>
      )}

      {/* Notification message (no questions / requiresResponse=false) */}
      {message && !message.requiresResponse && !isLoadingQuestions && (
        <div className="space-y-3">
          <p className="text-sm">{message.content}</p>
          <div className="flex justify-end">
            <Button
              variant="outline"
              size="sm"
              onClick={onDismissMessage}
              disabled={isDismissingMessage}
            >
              {isDismissingMessage ? "Dismissing..." : "Dismiss"}
            </Button>
          </div>
          {dismissMessageError && (
            <p className="text-sm text-destructive">
              Error: {dismissMessageError}
            </p>
          )}
        </div>
      )}

      {/* No questions and requires response -- message content only */}
      {message &&
        message.requiresResponse &&
        questions &&
        questions.length === 0 &&
        !isLoadingQuestions && (
          <div className="space-y-3">
            <p className="text-sm">{message.content}</p>
            <p className="text-xs text-muted-foreground">
              Waiting for structured questions...
            </p>
          </div>
        )}

      {/* Agent Logs Section */}
      {!logsOpen && (outputQuery.data?.length ?? 0) > 0 && (
        <div className="pt-2">
          <button
            className="flex items-center gap-2 text-xs text-muted-foreground hover:text-foreground"
            onClick={() => setLogsOpen(true)}
          >
            Show agent logs
            <span className="rounded-full bg-muted px-1.5 py-0.5 text-[10px] tabular-nums">
              {outputQuery.isLoading ? "…" : outputQuery.data?.length}
            </span>
          </button>
        </div>
      )}

      {logsOpen && (
        <div
          className="mt-2 overflow-y-auto rounded-md"
          style={{ maxHeight: 300 }}
          ref={logsContainerRef}
        >
          <AgentOutputViewer agentId={agent.id} />
        </div>
      )}
    </div>
  );
}
