"use client";

import { useCallback, useEffect, useState } from "react";
import { ChevronDown, ChevronUp, FileJson, FileText } from "lucide-react";
import type { SourceImpactResponse, SourceRecordDto } from "@/lib/api/types";
import { StemeDBClient } from "@/lib/api";
import { Button } from "@/components/ui/button";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetDescription,
} from "@/components/ui/sheet";
import { ImpactPreview } from "./impact-preview";

interface ImpactDetailPanelProps {
  isOpen: boolean;
  impact: SourceImpactResponse | null;
  onClose: () => void;
}

function CopyableHash({ hash }: { hash: string }) {
  const [copied, setCopied] = useState(false);
  const handleCopy = () => {
    navigator.clipboard.writeText(hash);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };
  return (
    <button
      onClick={handleCopy}
      className="font-mono text-xs cursor-pointer hover:text-foreground transition-colors"
      title="Click to copy full hash"
    >
      {hash.slice(0, 12)}...{hash.slice(-4)}
      <span className="ml-1 text-primary text-[10px]">
        {copied ? "Copied!" : ""}
      </span>
    </button>
  );
}

function CopyableAgent({ agent }: { agent: string }) {
  const [copied, setCopied] = useState(false);
  const handleCopy = () => {
    navigator.clipboard.writeText(agent);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };
  return (
    <button
      key={agent}
      onClick={handleCopy}
      className="px-2 py-1 rounded bg-muted text-xs font-mono cursor-pointer hover:text-foreground transition-colors"
      title="Click to copy agent ID"
    >
      {agent}
      <span className="ml-1 text-primary text-[10px]">
        {copied ? "Copied!" : ""}
      </span>
    </button>
  );
}

function StatusBadge({ status }: { status: string }) {
  const colorMap: Record<string, string> = {
    active: "bg-green-500/15 text-green-700 dark:text-green-400",
    inactive: "bg-muted text-muted-foreground",
    quarantined: "bg-red-500/15 text-red-700 dark:text-red-400",
    pending: "bg-yellow-500/15 text-yellow-700 dark:text-yellow-400",
  };
  const classes =
    colorMap[status.toLowerCase()] ?? "bg-muted text-muted-foreground";
  return (
    <span
      className={`inline-block px-2 py-0.5 rounded text-[11px] font-medium ${classes}`}
    >
      {status}
    </span>
  );
}

export function ImpactDetailPanel({
  isOpen,
  impact,
  onClose,
}: ImpactDetailPanelProps) {
  const [sourceRecord, setSourceRecord] = useState<SourceRecordDto | null>(
    null
  );
  const [contentExpanded, setContentExpanded] = useState(false);

  useEffect(() => {
    if (isOpen && impact?.source_hash) {
      const client = new StemeDBClient();
      client
        .getSource(impact.source_hash)
        .then(setSourceRecord)
        .catch(() => setSourceRecord(null));
    } else {
      setSourceRecord(null);
      setContentExpanded(false);
    }
  }, [isOpen, impact?.source_hash]);

  const handleExport = useCallback(
    (format: "csv" | "json") => {
      if (!impact) return;
      const client = new StemeDBClient();
      const url = client.getSourceImpactExportUrl(impact.source_hash, format);

      // Create a link with the export URL
      const a = document.createElement("a");
      a.href = url;
      a.download = `source-impact-${impact.source_hash.slice(0, 8)}.${format}`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    },
    [impact]
  );

  return (
    <Sheet open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <SheetContent side="right" className="w-full sm:max-w-lg overflow-y-auto">
        <SheetHeader>
          <SheetTitle>Impact Details</SheetTitle>
          {impact?.label && (
            <SheetDescription>{impact.label}</SheetDescription>
          )}
        </SheetHeader>

        {impact ? (
          <div className="mt-6 space-y-6">
            {/* Source Info */}
            <div className="rounded-lg border border-border p-4 space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-xs text-muted-foreground font-medium uppercase tracking-wide">
                  Source
                </span>
                <StatusBadge status={impact.status} />
              </div>
              <div className="text-muted-foreground">
                <CopyableHash hash={impact.source_hash} />
              </div>
              <div className="flex gap-4 pt-1">
                <div className="flex items-baseline gap-1.5">
                  <span className="text-xs text-muted-foreground">
                    Assertions
                  </span>
                  <span className="text-sm font-bold">
                    {impact.assertion_count}
                  </span>
                </div>
                <div className="flex items-baseline gap-1.5">
                  <span className="text-xs text-muted-foreground">Agents</span>
                  <span className="text-sm font-bold">
                    {impact.affected_agents.length}
                  </span>
                </div>
              </div>
            </div>

            {/* Export buttons - only when there's data to export */}
            {impact.assertion_count > 0 && (
              <div className="flex items-center gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handleExport("json")}
                >
                  <FileJson className="h-4 w-4 mr-1" />
                  Export JSON
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handleExport("csv")}
                >
                  <FileText className="h-4 w-4 mr-1" />
                  Export CSV
                </Button>
              </div>
            )}

            {/* Impact Summary */}
            <ImpactPreview impact={impact} />

            {/* Summary text */}
            <div className="rounded-lg bg-muted/50 p-4">
              <p className="text-sm text-muted-foreground">{impact.summary}</p>
            </div>

            {/* Source Content */}
            {sourceRecord?.content && (
              <div>
                <div className="flex items-center justify-between mb-2">
                  <h4 className="text-sm font-medium text-foreground">
                    Source Content
                    <span className="ml-2 text-xs text-muted-foreground font-normal">
                      ({sourceRecord.content.length.toLocaleString()} chars)
                    </span>
                  </h4>
                  <button
                    onClick={() => setContentExpanded(!contentExpanded)}
                    className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
                  >
                    {contentExpanded ? (
                      <>
                        Collapse <ChevronUp className="h-3 w-3" />
                      </>
                    ) : (
                      <>
                        Expand <ChevronDown className="h-3 w-3" />
                      </>
                    )}
                  </button>
                </div>
                <div
                  className={`rounded border border-border bg-muted/30 overflow-y-auto ${
                    contentExpanded ? "max-h-[600px]" : "max-h-96"
                  }`}
                >
                  <pre className="p-3 text-xs text-muted-foreground whitespace-pre-wrap font-mono leading-relaxed">
                    {sourceRecord.content}
                  </pre>
                </div>
              </div>
            )}

            {/* Affected Assertions */}
            {impact.affected_assertions.length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-foreground mb-3">
                  Affected Assertions ({impact.affected_assertions.length})
                </h4>
                <div className="max-h-48 overflow-y-auto rounded border border-border divide-y divide-border">
                  {impact.affected_assertions.map((hash, idx) => (
                    <div
                      key={hash}
                      className={`flex items-center px-3 py-2 ${
                        idx % 2 === 0 ? "bg-background" : "bg-muted/30"
                      } hover:bg-accent/10 transition-colors`}
                    >
                      <CopyableHash hash={hash} />
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Affected Agents */}
            {impact.affected_agents.length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-foreground mb-3">
                  Affected Agents ({impact.affected_agents.length})
                </h4>
                <div className="flex flex-wrap gap-2">
                  {impact.affected_agents.map((agent) => (
                    <CopyableAgent key={agent} agent={agent} />
                  ))}
                </div>
              </div>
            )}
          </div>
        ) : (
          <div className="mt-6 flex items-center justify-center py-8">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
          </div>
        )}
      </SheetContent>
    </Sheet>
  );
}
