"use client";

import { useParams } from "next/navigation";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { GedcomImport } from "@/components/gedcom-import";

export default function TreeGedcomPage() {
  const params = useParams<{ id: string }>();
  const treeId = params.id;

  async function exportGed() {
    const resp = await fetch(`/api/v1/trees/${treeId}/gedcom/export`, { credentials: "include" });
    if (!resp.ok) return;
    const blob = await resp.blob();
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "tree.ged";
    a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-semibold">Import &amp; export GEDCOM</h1>

      <GedcomImport fixedTreeId={treeId} />

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Export this tree</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          <p className="text-sm text-[var(--muted)]">
            Download this tree as a GEDCOM file — people, relationships, events, and sources.
          </p>
          <Button variant="outline" onClick={exportGed}>
            Download .ged
          </Button>
        </CardContent>
      </Card>
    </div>
  );
}
