"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { Copy, Megaphone, Pencil } from "lucide-react";
import { PageLayout } from "@/components/design-system/page-layout";
import { TemplatePreview } from "@/components/email-templates/template-preview";
import { TemplateActions } from "@/components/email-templates/template-actions";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { LAYOUT_THEME_LABELS } from "@/lib/email-builder/render";
import { CATEGORY_LABELS } from "@/lib/email-builder/starters";
import type { LayoutTheme } from "@/lib/email-builder/types";
import { useLocale } from "@/components/providers/locale-provider";

export function TemplateDetailClient({
  template,
  preview,
}: {
  template: {
    _id: string;
    name: string;
    description?: string;
    category?: string;
    subject: string;
    language: string;
    status: string;
    layoutTheme?: string;
    variables?: string[];
    designSettings?: Record<string, unknown>;
  };
  preview: {
    subject: string;
    htmlContent: string;
    textContent: string;
    variables: string[];
  };
}) {
  const router = useRouter();
  const { locale } = useLocale();
  const isAr = locale === "ar";
  const theme = template.layoutTheme as LayoutTheme | undefined;

  async function duplicate() {
    const res = await fetch(`/api/email-templates/${template._id}/duplicate`, {
      method: "POST",
    });
    const json = await res.json();
    if (res.ok && json.data?._id) {
      router.push(`/email-templates/${json.data._id}/edit`);
      router.refresh();
    }
  }

  return (
    <PageLayout
      title={template.name}
      description={template.description}
      actions={
        <div className="flex flex-wrap gap-2">
          <Button asChild variant="outline" size="sm">
            <Link href={`/email-templates/${template._id}/edit`}>
              <Pencil className="h-4 w-4" />
              {isAr ? "تعديل" : "Edit"}
            </Link>
          </Button>
          <Button type="button" variant="outline" size="sm" onClick={() => void duplicate()}>
            <Copy className="h-4 w-4" />
            {isAr ? "نسخ" : "Duplicate"}
          </Button>
          <Button asChild variant="outline" size="sm">
            <Link href={`/campaigns/new?templateId=${template._id}`}>
              <Megaphone className="h-4 w-4" />
              {isAr ? "استخدام في حملة" : "Use in campaign"}
            </Link>
          </Button>
          <TemplateActions id={template._id} />
        </div>
      }
    >
      <div className="flex flex-wrap gap-2">
        {template.category ? (
          <Badge variant="secondary">
            {isAr
              ? CATEGORY_LABELS[template.category]?.ar ?? template.category
              : CATEGORY_LABELS[template.category]?.en ?? template.category}
          </Badge>
        ) : null}
        {theme ? (
          <Badge variant="secondary">
            {isAr ? LAYOUT_THEME_LABELS[theme]?.ar : LAYOUT_THEME_LABELS[theme]?.en}
          </Badge>
        ) : null}
        <Badge>{template.status}</Badge>
        <Badge variant="secondary">{template.language}</Badge>
        <Badge variant="secondary">
          {template.variables?.length ?? 0} {isAr ? "متغيرات" : "vars"}
        </Badge>
      </div>

      <TemplatePreview
        subject={preview.subject}
        htmlContent={preview.htmlContent}
        textContent={preview.textContent}
      />

      <section className="surface-elevated p-4">
        <h3 className="text-sm font-semibold">{isAr ? "المتغيرات" : "Variables"}</h3>
        <div className="mt-2 flex flex-wrap gap-2">
          {(preview.variables ?? []).map((v) => (
            <code key={v} className="rounded-full bg-primary/10 px-2 py-1 text-xs text-primary">
              {`{{${v}}}`}
            </code>
          ))}
        </div>
      </section>
    </PageLayout>
  );
}
