"use client";

import { useState } from "react";
import type { WorkPackageOutput } from "@/lib/work-package-types";
import { SIMULATED_EXECUTION_DISCLAIMER } from "@/lib/work-package-types";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { MarkdownContent } from "@/components/MarkdownContent";
import { ChevronDown, ChevronUp } from "lucide-react";

export function WorkPackageOutputCard(props: {
  output: WorkPackageOutput;
  defaultOpen?: boolean;
}) {
  const { output, defaultOpen = false } = props;
  const [open, setOpen] = useState(defaultOpen);

  const disclaimer =
    output.disclaimer?.trim() || SIMULATED_EXECUTION_DISCLAIMER;

  return (
    <Card className="rounded-2xl border-0 bg-background/88 shadow-sm ring-1 ring-black/5">
      <CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0 p-3">
        <div className="min-w-0">
          <CardTitle className="truncate text-xs font-semibold">
            {output.title}
          </CardTitle>
          <div className="mt-1 flex flex-wrap items-center gap-1">
            <Badge variant="secondary" className="text-[11px]">
              {output.executionMode === "simulated"
                ? "Simulated Execution"
                : "LLM Automation"}
            </Badge>
            <Badge variant="outline" className="text-[11px]">
              {output.type}
            </Badge>
          </div>
        </div>
        <Button
          variant="ghost"
          size="icon"
          className="h-7 w-7 shrink-0"
          onClick={() => setOpen((v) => !v)}
          aria-label={open ? "Collapse output" : "Expand output"}
        >
          {open ? (
            <ChevronUp className="h-4 w-4" />
          ) : (
            <ChevronDown className="h-4 w-4" />
          )}
        </Button>
      </CardHeader>
      <CardContent className="space-y-2 p-3 pt-0">
        <div className="rounded-xl bg-muted/32 p-2.5 text-[11px] leading-5 text-muted-foreground">
          {disclaimer}
        </div>
        {open ? (
          <div className="rounded-xl bg-muted/18 p-3">
            <MarkdownContent content={output.content} />
          </div>
        ) : null}
      </CardContent>
    </Card>
  );
}
