"use client";

import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { Loader2 as Loader, Plus, RefreshCw, Pencil, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardBody, CardHeader, CardTitle } from "@/components/ui/card";
import { Input, Textarea, Label, Select } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";

type Template = {
  id: string;
  name: string;
  category: string | null;
  language: string | null;
  body: string;
  headerType: string | null;
  headerText: string | null;
  footerText: string | null;
  metaStatus: string | null;
  updatedAt: string;
};

export default function TemplatesPage() {
  const [templates, setTemplates] = useState<Template[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [showForm, setShowForm] = useState(false);
  const [syncing, setSyncing] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState<Template | null>(null);

  async function sync() {
    setSyncing(true);
    const res = await fetch("/api/templates/sync", { method: "POST" });
    const j = await res.json().catch(() => ({}));
    setSyncing(false);
    if (!res.ok) return toast.error(j.error ?? "Sync failed.");
    toast.success(`Synced ${j.count} templates from Meta.`);
    load();
  }

  const load = useCallback(async () => {
    setLoading(true);
    const res = await fetch("/api/templates");
    const j = await res.json().catch(() => ({}));
    if (res.ok) setTemplates(j.templates ?? []);
    else toast.error(j.error ?? "Failed to load templates.");
    setLoading(false);
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setSaving(true);
    const form = e.currentTarget;
    const data: Record<string, string> = {};
    for (const [k, v] of new FormData(form).entries()) data[k] = String(v);
    data.category = data.category || "UTILITY";
    data.language = data.language || "en";
    data.headerType = data.headerType || "TEXT";
    
    const url = editingTemplate ? `/api/templates/${editingTemplate.id}` : "/api/templates";
    const method = editingTemplate ? "PUT" : "POST";
    
    const res = await fetch(url, {
      method,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    });
    
    const j = await res.json().catch(() => ({}));
    setSaving(false);
    
    if (!res.ok) return toast.error(j.error ?? `${editingTemplate ? "Update" : "Create"} failed.`);
    
    toast.success(`Template ${editingTemplate ? "updated" : "created"}.`);
    closeForm();
    load();
  }

  async function handleDelete(id: string) {
    if (!confirm("Are you sure you want to delete this template from Meta and locally?")) return;
    
    const res = await fetch(`/api/templates/${id}`, { method: "DELETE" });
    const j = await res.json().catch(() => ({}));
    
    if (!res.ok) return toast.error(j.error ?? "Delete failed.");
    toast.success("Template deleted.");
    load();
  }

  function openEdit(t: Template) {
    setEditingTemplate(t);
    setShowForm(true);
  }

  function closeForm() {
    setShowForm(false);
    setEditingTemplate(null);
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold text-foreground">Message templates</h2>
          <p className="text-sm text-muted-foreground">
            Templates are used by broadcasts. For live Meta sending, name them exactly as approved templates in
            your WABA.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={sync} size="sm" loading={syncing}>
            <RefreshCw className="h-4 w-4 mr-2" /> Sync Meta templates
          </Button>
          <Button onClick={() => { setEditingTemplate(null); setShowForm((v) => !v); }} size="sm">
            <Plus className="h-4 w-4 mr-2" /> New template
          </Button>
        </div>
      </div>

      {showForm && (
        <Card>
          <CardHeader>
            <CardTitle>{editingTemplate ? "Edit Template" : "Create Template"}</CardTitle>
          </CardHeader>
          <CardBody>
            <form onSubmit={handleSubmit} className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <div>
                <Label>Name</Label>
                <Input name="name" required defaultValue={editingTemplate?.name} readOnly={!!editingTemplate} className={editingTemplate ? "bg-muted" : ""} />
                {editingTemplate && <p className="text-xs text-muted-foreground mt-1">Template name cannot be edited.</p>}
              </div>
              <div>
                <Label>Language</Label>
                <Input name="language" required defaultValue={editingTemplate?.language || "en"} placeholder="e.g. en, en_US, es" />
              </div>
              <div>
                <Label>Category</Label>
                <Select name="category" defaultValue={editingTemplate?.category || "UTILITY"}>
                  <option value="UTILITY">Utility</option>
                  <option value="MARKETING">Marketing</option>
                  <option value="AUTHENTICATION">Authentication</option>
                </Select>
              </div>
              <div>
                <Label>Header Type</Label>
                <Select name="headerType" defaultValue={editingTemplate?.headerType || "TEXT"}>
                  <option value="NONE">None</option>
                  <option value="TEXT">Text</option>
                  <option value="IMAGE">Image</option>
                  <option value="VIDEO">Video</option>
                  <option value="DOCUMENT">Document</option>
                </Select>
              </div>
              <div className="md:col-span-2">
                <Label>Header text (optional)</Label>
                <Input name="headerText" defaultValue={editingTemplate?.headerText || ""} placeholder="e.g. Your promo code is here" />
              </div>
              <div className="md:col-span-2">
                <Label>Body</Label>
                <Textarea name="body" defaultValue={editingTemplate?.body} rows={3} placeholder="Hi {{1}}, your order {{2}} has shipped." required />
              </div>
              <div className="md:col-span-2">
                <Label>Footer text (optional)</Label>
                <Input name="footerText" defaultValue={editingTemplate?.footerText || ""} placeholder="e.g. Reply STOP to unsubscribe" />
              </div>
              <div className="md:col-span-2 flex justify-end gap-2">
                <Button type="button" variant="outline" onClick={closeForm}>
                  Cancel
                </Button>
                <Button type="submit" loading={saving}>
                  {editingTemplate ? "Update" : "Create"}
                </Button>
              </div>
            </form>
          </CardBody>
        </Card>
      )}

      <Card>
        <CardBody>
          {loading ? (
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Loader className="h-4 w-4 animate-spin" /> Loading…
            </div>
          ) : templates.length === 0 ? (
            <p className="text-sm text-muted-foreground">No templates yet.</p>
          ) : (
            <div className="space-y-3">
              {templates.map((t) => (
                <div key={t.id} className="rounded-lg border border-border px-4 py-3">
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-semibold text-foreground">{t.name}</span>
                    <Badge tone="indigo">{t.category ?? "UTILITY"}</Badge>
                    <Badge tone="slate">{t.language ?? "en"}</Badge>
                    <Badge
                      tone={t.metaStatus === "APPROVED" ? "green" : t.metaStatus === "REJECTED" ? "red" : "amber"}
                    >
                      {t.metaStatus ?? "DRAFT"}
                    </Badge>
                    <span className="ml-auto text-xs text-muted-foreground mr-2">
                      {new Date(t.updatedAt).toLocaleDateString()}
                    </span>
                    <Button variant="ghost" size="icon" className="h-8 w-8 text-muted-foreground hover:text-foreground" onClick={() => openEdit(t)}>
                      <Pencil className="h-4 w-4" />
                    </Button>
                    <Button variant="ghost" size="icon" className="h-8 w-8 text-red-500 hover:bg-red-50 hover:text-red-600" onClick={() => handleDelete(t.id)}>
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                  <p className="mt-1.5 whitespace-pre-wrap text-sm text-muted-foreground">{t.body}</p>
                </div>
              ))}
            </div>
          )}
        </CardBody>
      </Card>
    </div>
  );
}
