"use client";

import { useMemo, useState } from "react";
import { Copy, Download, FileArchive } from "lucide-react";
import { Button } from "@/shared/components/ui/button";
import type { XmlGeneratorConfig } from "../types";
import {
  generateAllCategories,
  downloadXmlFile,
  downloadZipAll,
} from "../services/xml-generator";

interface XmlPreviewProps {
  config: XmlGeneratorConfig;
}

export function XmlPreview({ config }: XmlPreviewProps) {
  const [copied, setCopied] = useState<"xml" | "xpath" | null>(null);

  const allOutputs = useMemo(
    () =>
      generateAllCategories(
        config.categories,
        config.baseNamespace,
        config.mode,
      ),
    [config.categories, config.baseNamespace, config.mode],
  );

  const current = allOutputs[config.currentCategory];
  const xml = current?.xml || "";
  const xpaths = current?.xpaths || "";

  const handleCopy = async (text: string, type: "xml" | "xpath") => {
    try {
      await navigator.clipboard.writeText(text);
      setCopied(type);
      setTimeout(() => setCopied(null), 2000);
    } catch {
      // silent
    }
  };

  const safeCatName = (config.currentCategory || "unknown")
    .replace(/\s+/g, "_")
    .replace(/[^A-Za-z0-9_.-]/g, "");

  const handleDownloadCurrent = () => {
    if (!xml) return;
    downloadXmlFile(xml, `${safeCatName}Data.xml`);
  };

  const handleDownloadZip = async () => {
    await downloadZipAll(config.categories, config.baseNamespace, config.mode);
  };

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center gap-2">
        <h2 className="text-lg font-semibold">Preview & Export</h2>
        <div className="ml-auto flex gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={handleDownloadCurrent}
            disabled={!xml}
          >
            <Download className="mr-1 h-4 w-4" /> XML curent
          </Button>
          <Button size="sm" onClick={handleDownloadZip}>
            <FileArchive className="mr-1 h-4 w-4" /> ZIP toate
          </Button>
        </div>
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        {/* XML preview */}
        <div>
          <div className="mb-1.5 flex items-center justify-between">
            <span className="text-xs font-medium text-muted-foreground">
              XML — {config.currentCategory}
            </span>
            <Button
              variant="ghost"
              size="sm"
              className="h-6 text-xs"
              onClick={() => handleCopy(xml, "xml")}
              disabled={!xml}
            >
              <Copy className="mr-1 h-3 w-3" />
              {copied === "xml" ? "Copiat!" : "Copiază"}
            </Button>
          </div>
          <pre className="max-h-80 overflow-auto rounded-lg border bg-muted/30 p-3 text-xs">
            {xml ||
              "<!-- Niciun XML generat. Adaugă câmpuri în categoria curentă. -->"}
          </pre>
        </div>

        {/* XPath preview */}
        <div>
          <div className="mb-1.5 flex items-center justify-between">
            <span className="text-xs font-medium text-muted-foreground">
              XPaths — {config.currentCategory}
            </span>
            <Button
              variant="ghost"
              size="sm"
              className="h-6 text-xs"
              onClick={() => handleCopy(xpaths, "xpath")}
              disabled={!xpaths}
            >
              <Copy className="mr-1 h-3 w-3" />
              {copied === "xpath" ? "Copiat!" : "Copiază"}
            </Button>
          </div>
          <pre className="max-h-80 overflow-auto rounded-lg border bg-muted/30 p-3 text-xs">
            {xpaths || ""}
          </pre>
        </div>
      </div>
    </div>
  );
}
