"use client";

import { useCallback } from "react";
import { Download, FileJson, FileText } from "lucide-react";
import type { SourceImpactResponse } 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;
}

export function ImpactDetailPanel({
  isOpen,
  impact,
  onClose,
}: ImpactDetailPanelProps) {
  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">
            {/* Export buttons */}
            <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>

            {/* 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">
                  <table className="w-full text-sm">
                    <thead className="sticky top-0 bg-muted/50">
                      <tr>
                        <th className="text-left px-3 py-2 font-medium text-muted-foreground">
                          Hash
                        </th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {impact.affected_assertions.map((hash) => (
                        <tr key={hash} className="hover:bg-accent/5">
                          <td className="px-3 py-2 font-mono text-xs">
                            {hash}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </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) => (
                    <span
                      key={agent}
                      className="px-2 py-1 rounded bg-muted text-xs font-mono"
                    >
                      {agent}
                    </span>
                  ))}
                </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>
  );
}
