"use client";

import Link from "next/link";
import { useState } from "react";
import { GitBranch, Share2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { CrossPedigreeProvider } from "../../cross-pedigree/CrossPedigreeContext";
import { PedigreeEdgePanel } from "../../cross-pedigree/components/PedigreeEdgePanel";
import { PedigreeNodeFormPanel } from "../../cross-pedigree/components/PedigreeNodeFormPanel";

interface GermplasmPedigreePanelProps {
  germplasmDbId: string;
  germplasmName?: string | null;
}

function GermplasmPedigreePanelContent({ germplasmDbId, germplasmName }: GermplasmPedigreePanelProps) {
  const [refreshKey, setRefreshKey] = useState(0);
  const bumpRefresh = () => setRefreshKey((value) => value + 1);

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap gap-2">
        <Button asChild variant="outline" size="sm" className="w-fit">
          <Link href={`/germplasm/cross-pedigree/pedigree-nodes/${encodeURIComponent(germplasmDbId)}`}>
            <Share2 className="mr-2 h-4 w-4" />
            节点详情页
          </Link>
        </Button>
        <Button asChild variant="outline" size="sm" className="w-fit">
          <Link href="/germplasm/cross-pedigree?tab=pedigree-nodes">
            <GitBranch className="mr-2 h-4 w-4" />
            全局 Pedigree 管理
          </Link>
        </Button>
      </div>

      <PedigreeNodeFormPanel
        key={`node-${refreshKey}`}
        scopeGermplasmDbId={germplasmDbId}
        scopeGermplasmName={germplasmName}
        compact
        onChanged={bumpRefresh}
      />

      <PedigreeEdgePanel
        key={`edge-${refreshKey}`}
        scopeGermplasmDbId={germplasmDbId}
        compact
        onChanged={bumpRefresh}
      />
    </div>
  );
}

export function GermplasmPedigreePanel(props: GermplasmPedigreePanelProps) {
  return (
    <CrossPedigreeProvider>
      <GermplasmPedigreePanelContent {...props} />
    </CrossPedigreeProvider>
  );
}
