"use client";

import { Plus, Trash2, ChevronUp, ChevronDown } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  createDefaultCta,
  normalizeDesignSettings,
} from "@/lib/email-builder/design-settings";
import type { EmailCtaButton, EmailDesignSettings } from "@/lib/email-builder/types";
import { useLocale } from "@/components/providers/locale-provider";

export function CtaManager({
  designSettings,
  onChange,
}: {
  designSettings: EmailDesignSettings;
  onChange: (next: EmailDesignSettings) => void;
}) {
  const { locale } = useLocale();
  const isAr = locale === "ar";
  const normalized = normalizeDesignSettings(designSettings);
  const ctas = normalized.ctas ?? [];

  function updateCtas(next: EmailCtaButton[]) {
    onChange({ ...designSettings, ctas: next });
  }

  function updateCta(id: string, patch: Partial<EmailCtaButton>) {
    updateCtas(ctas.map((c) => (c.id === id ? { ...c, ...patch } : c)));
  }

  function moveCta(id: string, dir: -1 | 1) {
    const idx = ctas.findIndex((c) => c.id === id);
    if (idx < 0) return;
    const target = idx + dir;
    if (target < 0 || target >= ctas.length) return;
    const copy = [...ctas];
    const [item] = copy.splice(idx, 1);
    copy.splice(target, 0, item);
    updateCtas(copy);
  }

  return (
    <section className="surface-elevated space-y-3 p-4">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <h3 className="text-sm font-semibold">
          {isAr ? "أزرار CTA" : "CTA buttons"}
        </h3>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={() => updateCtas([...ctas, createDefaultCta()])}
        >
          <Plus className="h-4 w-4" />
          {isAr ? "إضافة زر" : "Add CTA"}
        </Button>
      </div>

      {ctas.length === 0 ? (
        <p className="text-sm text-muted-foreground">
          {isAr ? "لا توجد أزرار. أضف زراً واحداً على الأقل." : "No CTAs yet."}
        </p>
      ) : null}

      {ctas.map((cta, index) => (
        <div
          key={cta.id}
          className="rounded-xl border border-border bg-muted/20 p-3 space-y-2"
        >
          <div className="flex flex-wrap items-center justify-between gap-2">
            <span className="text-xs font-medium text-muted-foreground">
              {isAr ? `زر ${index + 1}` : `Button ${index + 1}`}
            </span>
            <div className="flex gap-1">
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="h-8 w-8"
                disabled={index === 0}
                onClick={() => moveCta(cta.id, -1)}
              >
                <ChevronUp className="h-4 w-4" />
              </Button>
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="h-8 w-8"
                disabled={index === ctas.length - 1}
                onClick={() => moveCta(cta.id, 1)}
              >
                <ChevronDown className="h-4 w-4" />
              </Button>
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="h-8 w-8 text-destructive"
                onClick={() => updateCtas(ctas.filter((c) => c.id !== cta.id))}
              >
                <Trash2 className="h-4 w-4" />
              </Button>
            </div>
          </div>
          <div className="grid gap-2 sm:grid-cols-2">
            <Input
              placeholder={isAr ? "نص الزر" : "Button text"}
              value={cta.text}
              onChange={(e) => updateCta(cta.id, { text: e.target.value })}
            />
            <Input
              placeholder="https://"
              dir="ltr"
              value={cta.url}
              onChange={(e) => updateCta(cta.id, { url: e.target.value })}
            />
            <select
              className="flex h-10 rounded-lg border border-border bg-card px-3 text-sm"
              value={cta.style}
              onChange={(e) =>
                updateCta(cta.id, {
                  style: e.target.value as EmailCtaButton["style"],
                })
              }
            >
              <option value="primary">Primary</option>
              <option value="secondary">Secondary</option>
              <option value="outline">Outline</option>
              <option value="ghost">Ghost</option>
            </select>
            <select
              className="flex h-10 rounded-lg border border-border bg-card px-3 text-sm"
              value={cta.align}
              onChange={(e) =>
                updateCta(cta.id, { align: e.target.value as EmailCtaButton["align"] })
              }
            >
              <option value="start">{isAr ? "يمين" : "Start"}</option>
              <option value="center">{isAr ? "وسط" : "Center"}</option>
              <option value="end">{isAr ? "يسار" : "End"}</option>
            </select>
            <select
              className="flex h-10 rounded-lg border border-border bg-card px-3 text-sm"
              value={cta.width ?? "auto"}
              onChange={(e) =>
                updateCta(cta.id, { width: e.target.value as EmailCtaButton["width"] })
              }
            >
              <option value="auto">{isAr ? "عرض تلقائي" : "Auto width"}</option>
              <option value="full">{isAr ? "عرض كامل" : "Full width"}</option>
            </select>
            <Input
              type="number"
              min={0}
              max={24}
              placeholder={isAr ? "انحناء الحواف" : "Radius"}
              value={cta.borderRadius ?? 8}
              onChange={(e) =>
                updateCta(cta.id, { borderRadius: Number(e.target.value) || 8 })
              }
            />
            <Input
              type="color"
              value={cta.backgroundColor ?? designSettings.primaryColor}
              onChange={(e) => updateCta(cta.id, { backgroundColor: e.target.value })}
              className="h-10"
            />
            <Input
              type="color"
              value={cta.textColor ?? "#ffffff"}
              onChange={(e) => updateCta(cta.id, { textColor: e.target.value })}
              className="h-10"
            />
          </div>
        </div>
      ))}
    </section>
  );
}
