"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import AppShell from "@/components/AppShell";
import { crmApi, type DocumentTemplate } from "@/lib/crmApi";

// ── Starter templates ────────────────────────────────────────────────────────
const STARTER_TEMPLATES: Record<string, Record<string, string>> = {
  NDA: {
    default: `<div class="section-title">1. Introduction</div>
<p>This Non-Disclosure Agreement is entered into on <strong>{{contract_date}}</strong> between <strong>{{company_name}}</strong> ("Disclosing Party") and <strong>{{client_name}}</strong> of <strong>{{client_address}}</strong> ("Receiving Party").</p>

<div class="section-title">2. Confidential Information</div>
<p>Confidential Information includes business plans, financial data, client lists, marketing strategies, and any information designated as confidential.</p>

<div class="section-title">3. Obligations</div>
<ul>
  <li>Hold all Confidential Information in strict confidence.</li>
  <li>Not disclose to any third party without prior written consent.</li>
  <li>Use solely for evaluating the potential business relationship.</li>
</ul>

<div class="section-title">4. Duration</div>
<p>This Agreement remains effective for <strong>two (2) years</strong> from the date of signing.</p>

<div class="section-title">5. Governing Law</div>
<p>This Agreement is governed by applicable laws.</p>`,
  },
  Contract: {
    "Website Only": `<div class="section-title">1. Project Overview</div>
<p>This Agreement is entered into on <strong>{{contract_date}}</strong> between <strong>{{company_name}}</strong> ("Agency") and <strong>{{client_name}}</strong> of <strong>{{client_address}}</strong> ("Client").</p>

<div class="section-title">2. Scope of Work</div>
<ul>
  <li>Custom website design — up to 5 pages.</li>
  <li>Fully responsive design (mobile, tablet, desktop).</li>
  <li>SEO-friendly structure and meta tag optimization.</li>
  <li>Contact forms and social media integration.</li>
</ul>

<div class="section-title">3. Payment Terms</div>
<p>Total project value: <strong>{{amount}}</strong></p>
<ul>
  <li><strong>50%</strong> — Advance upon signing.</li>
  <li><strong>50%</strong> — Upon delivery.</li>
</ul>

<div class="section-title">4. Timeline</div>
<p>Estimated delivery: <strong>{{delivery_date}}</strong>.</p>

<div class="section-title">5. Revisions</div>
<p>Includes <strong>3 rounds</strong> of revisions.</p>

<div class="section-title">6. Ownership</div>
<p>Full ownership transfers to Client upon receipt of final payment.</p>`,

    "Website + Branding": `<div class="section-title">1. Project Overview</div>
<p>This Agreement, dated <strong>{{contract_date}}</strong>, is between <strong>{{company_name}}</strong> ("Agency") and <strong>{{client_name}}</strong> ("Client") for a complete Website and Brand Identity package.</p>

<div class="section-title">2. Branding Scope</div>
<ul>
  <li>Logo design — up to 3 concepts with revisions.</li>
  <li>Brand color palette and typography.</li>
  <li>Business card and letterhead design.</li>
  <li>Brand guidelines document (PDF).</li>
</ul>

<div class="section-title">3. Website Scope</div>
<ul>
  <li>Custom website — up to 7 pages.</li>
  <li>Responsive layout, SEO-optimized.</li>
  <li>Brand-consistent design using approved assets.</li>
</ul>

<div class="section-title">4. Payment Terms</div>
<p>Total: <strong>{{amount}}</strong> — 50% advance, 25% on brand approval, 25% on launch.</p>

<div class="section-title">5. Timeline</div>
<p>Estimated delivery: <strong>{{delivery_date}}</strong>.</p>`,

    "Branding Only": `<div class="section-title">1. Project Overview</div>
<p>This Branding Agreement is made on <strong>{{contract_date}}</strong> between <strong>{{company_name}}</strong> ("Agency") and <strong>{{client_name}}</strong> ("Client").</p>

<div class="section-title">2. Deliverables</div>
<ul>
  <li>Logo design — 3 concepts, final in PNG/SVG/PDF.</li>
  <li>Brand color palette with HEX, RGB, CMYK codes.</li>
  <li>Typography selection and usage guide.</li>
  <li>Business card design (front and back).</li>
  <li>Letterhead design (A4).</li>
  <li>Brand guidelines document (PDF).</li>
</ul>

<div class="section-title">3. Payment Terms</div>
<p>Total: <strong>{{amount}}</strong> — 50% advance, 50% on delivery.</p>

<div class="section-title">4. Timeline</div>
<p>Initial concepts within 7 business days. Full delivery: <strong>{{delivery_date}}</strong>.</p>

<div class="section-title">5. Ownership</div>
<p>All files transfer to Client upon full payment.</p>`,

    default: `<div class="section-title">1. Parties</div>
<p>This Agreement is entered into on <strong>{{contract_date}}</strong> between <strong>{{company_name}}</strong> ("Service Provider") and <strong>{{client_name}}</strong> ("Client").</p>

<div class="section-title">2. Scope of Services</div>
<ul>
  <li>Service description here.</li>
  <li>Deliverables and timeline.</li>
</ul>

<div class="section-title">3. Payment</div>
<p>Total: <strong>{{amount}}</strong> — 50% advance, 50% on completion.</p>

<div class="section-title">4. Timeline</div>
<p>Delivery by: <strong>{{delivery_date}}</strong>.</p>`,
  },
};

const PLACEHOLDERS = [
  { label: "Client Name",    value: "{{client_name}}" },
  { label: "Company Name",   value: "{{company_name}}" },
  { label: "Price",          value: "{{price}}" },
  { label: "Amount",         value: "{{amount}}" },
  { label: "Contract No.",   value: "{{contract_number}}" },
  { label: "Client Address", value: "{{client_address}}" },
  { label: "Contract Date",  value: "{{contract_date}}" },
  { label: "Delivery Date",  value: "{{delivery_date}}" },
];

const CATEGORY_COLORS: Record<string, string> = {
  NDA:      "bg-amber-50 text-amber-700 border border-amber-200",
  Contract: "bg-blue-50 text-blue-700 border border-blue-200",
};

const SUB_COLORS: Record<string, string> = {
  "Website Only":       "bg-emerald-50 text-emerald-700 border border-emerald-200",
  "Website + Branding": "bg-purple-50 text-purple-700 border border-purple-200",
  "Branding Only":      "bg-pink-50 text-pink-700 border border-pink-200",
};

function Badge({ label, colorClass }: { label: string; colorClass?: string }) {
  return (
    <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-[11px] font-semibold ${colorClass ?? "bg-neutral-100 text-neutral-600 border border-neutral-200"}`}>
      {label}
    </span>
  );
}

export default function DocumentTemplatesPage() {
  const [templates, setTemplates]   = useState<DocumentTemplate[]>([]);
  const [loading, setLoading]       = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError]           = useState<string | null>(null);
  const [success, setSuccess]       = useState(false);
  const [expanded, setExpanded]     = useState<number | null>(null);

  const [name, setName]             = useState("");
  const [type, setType]             = useState("invoice");
  const [content, setContent]       = useState("");
  const [category, setCategory]     = useState("");
  const [subCategory, setSubCategory] = useState("");

  const textareaRef = useRef<HTMLTextAreaElement>(null);

  const canCreate = useMemo(
    () => name.trim().length > 1 && type.trim().length > 0 && content.trim().length > 5 && !submitting,
    [content, name, submitting, type],
  );

  function loadStarter(cat: string, sub: string) {
    const catMap = STARTER_TEMPLATES[cat];
    if (!catMap) { setContent(""); return; }
    setContent(catMap[sub] ?? catMap["default"] ?? "");
  }

  function handleCategoryChange(val: string) {
    setCategory(val);
    setSubCategory("");
    loadStarter(val, "");
  }

  function handleSubCategoryChange(val: string) {
    setSubCategory(val);
    loadStarter(category, val);
  }

  function insertPlaceholder(ph: string) {
    const ta = textareaRef.current;
    if (!ta) { setContent((c) => c + ph); return; }
    const start = ta.selectionStart;
    const end   = ta.selectionEnd;
    const next  = content.substring(0, start) + ph + content.substring(end);
    setContent(next);
    setTimeout(() => {
      ta.focus();
      ta.setSelectionRange(start + ph.length, start + ph.length);
    }, 0);
  }

  async function refresh() {
    setError(null);
    setLoading(true);
    try {
      const res = await crmApi.templates.list();
      setTemplates(res ?? []);
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Failed to load templates.");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => { void refresh(); }, []);

  async function onCreate(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    if (!canCreate) return;
    setSubmitting(true);
    setError(null);
    setSuccess(false);
    try {
      await crmApi.templates.create({
        name: name.trim(),
        type: type.trim(),
        category,
        sub_category: subCategory,
        content,
      });
      setName(""); setCategory(""); setSubCategory(""); setContent(""); setType("invoice");
      setSuccess(true);
      setTimeout(() => setSuccess(false), 4000);
      await refresh();
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Failed to create template.");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <AppShell title="Templates" subtitle="Manage reusable document templates for the active company.">

      {/* ── Alerts ── */}
      {error && (
        <div className="mb-5 flex items-start gap-3 rounded-xl border border-red-200 bg-red-50 px-4 py-3">
          <svg className="mt-0.5 h-4 w-4 shrink-0 text-red-500" viewBox="0 0 24 24" fill="none">
            <path d="M12 9v4m0 4h.01M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          <p className="text-sm text-red-700">{error}</p>
        </div>
      )}
      {success && (
        <div className="mb-5 flex items-center gap-3 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3">
          <svg className="h-4 w-4 shrink-0 text-emerald-500" viewBox="0 0 24 24" fill="none">
            <path d="M20 6 9 17l-5-5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          <p className="text-sm font-medium text-emerald-700">Template created successfully!</p>
        </div>
      )}

      <div className="grid grid-cols-1 gap-6 xl:grid-cols-[1fr_400px]">

        {/* ══════════════════════════════════════════
            LEFT — Template Library
        ══════════════════════════════════════════ */}
        <div className="space-y-4">

          {/* Header card */}
          <div className="flex items-center justify-between rounded-xl border border-neutral-200 bg-white px-6 py-4 shadow-sm">
            <div>
              <p className="text-xs font-semibold uppercase tracking-widest text-neutral-400">Library</p>
              <p className="mt-1 text-sm text-neutral-500">
                {loading ? "Loading…" : `${templates.length} template${templates.length !== 1 ? "s" : ""} in active company`}
              </p>
            </div>
            <button
              type="button"
              onClick={() => void refresh()}
              disabled={loading}
              className="flex items-center gap-2 rounded-lg border border-neutral-200 bg-white px-4 py-2 text-sm font-semibold text-neutral-700 shadow-sm hover:bg-neutral-50 active:bg-neutral-100 disabled:opacity-50"
            >
              <svg className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} viewBox="0 0 24 24" fill="none">
                <path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                <path d="M21 3v5h-5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
              Refresh
            </button>
          </div>

          {/* Template list */}
          {loading ? (
            <div className="space-y-3">
              {[1,2,3].map((i) => (
                <div key={i} className="h-24 animate-pulse rounded-xl border border-neutral-200 bg-neutral-100" />
              ))}
            </div>
          ) : templates.length === 0 ? (
            <div className="rounded-xl border-2 border-dashed border-neutral-200 bg-white px-6 py-16 text-center">
              <svg className="mx-auto h-10 w-10 text-neutral-300" viewBox="0 0 24 24" fill="none">
                <path d="M7 3h7l3 3v15a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/>
                <path d="M14 3v4h4M9 12h6M9 16h4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
              </svg>
              <p className="mt-3 text-sm font-semibold text-neutral-500">No templates yet</p>
              <p className="mt-1 text-xs text-neutral-400">Create your first template using the form on the right.</p>
            </div>
          ) : (
            <div className="space-y-3">
              {templates.map((t) => {
                const isOpen = expanded === t.id;
                return (
                  <div key={t.id} className="overflow-hidden rounded-xl border border-neutral-200 bg-white shadow-sm transition-shadow hover:shadow-md">
                    <button
                      type="button"
                      onClick={() => setExpanded(isOpen ? null : t.id)}
                      className="flex w-full items-start justify-between gap-4 px-5 py-4 text-left"
                    >
                      <div className="min-w-0 flex-1">
                        <div className="flex flex-wrap items-center gap-2">
                          <p className="text-sm font-semibold text-neutral-900">{t.name}</p>
                          {t.category && (
                            <Badge label={t.category} colorClass={CATEGORY_COLORS[t.category]} />
                          )}
                          {t.sub_category && (
                            <Badge label={t.sub_category} colorClass={SUB_COLORS[t.sub_category]} />
                          )}
                        </div>
                        <p className="mt-1 text-xs text-neutral-400">Type: {t.type} · ID {t.id}</p>
                      </div>
                      <div className="flex shrink-0 items-center gap-2">
                        <svg
                          className={`h-4 w-4 text-neutral-400 transition-transform ${isOpen ? "rotate-180" : ""}`}
                          viewBox="0 0 24 24" fill="none"
                        >
                          <path d="m6 9 6 6 6-6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                      </div>
                    </button>

                    {isOpen && (
                      <div className="border-t border-neutral-100 px-5 pb-4 pt-3">
                        <p className="mb-2 text-xs font-semibold uppercase tracking-wider text-neutral-400">Content Preview</p>
                        <pre className="max-h-52 overflow-auto whitespace-pre-wrap rounded-lg border border-neutral-100 bg-neutral-50 p-3 font-mono text-[11px] leading-relaxed text-neutral-600">
                          {t.content}
                        </pre>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* ══════════════════════════════════════════
            RIGHT — Create Template
        ══════════════════════════════════════════ */}
        <div className="rounded-xl border border-neutral-200 bg-white shadow-sm">
          {/* Form header */}
          <div className="border-b border-neutral-100 px-6 py-5">
            <p className="text-xs font-semibold uppercase tracking-widest text-neutral-400">Admin</p>
            <h2 className="mt-1 text-base font-semibold text-neutral-900">Create template</h2>
            <p className="mt-0.5 text-xs text-neutral-500">Category select karo — content auto-load hoga.</p>
          </div>

          <form onSubmit={onCreate} className="space-y-5 px-6 py-5">

            {/* Category */}
            <div className="space-y-1.5">
              <label className="text-xs font-semibold uppercase tracking-wider text-neutral-500">Category</label>
              <select
                value={category}
                onChange={(e) => handleCategoryChange(e.target.value)}
                className="h-10 w-full rounded-lg border border-neutral-200 bg-white px-3 text-sm text-neutral-800 outline-none focus:border-[#0b1f3a] focus:ring-1 focus:ring-[#0b1f3a]/10"
              >
                <option value="">Select category…</option>
                <option value="NDA">NDA</option>
                <option value="Contract">Contract</option>
              </select>
            </div>

            {/* Sub Category — only for Contract */}
            {category === "Contract" && (
              <div className="space-y-1.5">
                <label className="text-xs font-semibold uppercase tracking-wider text-neutral-500">Sub Category</label>
                <select
                  value={subCategory}
                  onChange={(e) => handleSubCategoryChange(e.target.value)}
                  className="h-10 w-full rounded-lg border border-neutral-200 bg-white px-3 text-sm text-neutral-800 outline-none focus:border-[#0b1f3a] focus:ring-1 focus:ring-[#0b1f3a]/10"
                >
                  <option value="">Select sub category…</option>
                  <option value="Website Only">Website Only</option>
                  <option value="Website + Branding">Website + Branding</option>
                  <option value="Branding Only">Branding Only</option>
                </select>
              </div>
            )}

            {/* Name */}
            <div className="space-y-1.5">
              <label className="text-xs font-semibold uppercase tracking-wider text-neutral-500">Template Name</label>
              <input
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="e.g. Nuqoosh NDA 2026"
                className="h-10 w-full rounded-lg border border-neutral-200 bg-white px-3 text-sm text-neutral-800 outline-none placeholder:text-neutral-300 focus:border-[#0b1f3a] focus:ring-1 focus:ring-[#0b1f3a]/10"
              />
            </div>

            {/* Type */}
            <div className="space-y-1.5">
              <label className="text-xs font-semibold uppercase tracking-wider text-neutral-500">Type</label>
              <input
                value={type}
                onChange={(e) => setType(e.target.value)}
                placeholder="invoice"
                className="h-10 w-full rounded-lg border border-neutral-200 bg-white px-3 text-sm text-neutral-800 outline-none placeholder:text-neutral-300 focus:border-[#0b1f3a] focus:ring-1 focus:ring-[#0b1f3a]/10"
              />
            </div>

            {/* Placeholder inserter */}
            <div className="space-y-1.5">
              <label className="text-xs font-semibold uppercase tracking-wider text-neutral-500">
                Insert Variable
              </label>
              <p className="text-[11px] text-neutral-400">Content mein cursor rakh ke koi bhi button dabao.</p>
              <div className="flex flex-wrap gap-1.5">
                {PLACEHOLDERS.map((p) => (
                  <button
                    key={p.value}
                    type="button"
                    onClick={() => insertPlaceholder(p.value)}
                    className="rounded-md border border-neutral-200 bg-neutral-50 px-2.5 py-1 text-[11px] font-semibold text-neutral-600 transition hover:border-[#0b1f3a] hover:bg-[#0b1f3a] hover:text-white"
                  >
                    {p.label}
                  </button>
                ))}
              </div>
            </div>

            {/* Content */}
            <div className="space-y-1.5">
              <div className="flex items-center justify-between">
                <label className="text-xs font-semibold uppercase tracking-wider text-neutral-500">Content (HTML)</label>
                {content && (
                  <span className="text-[11px] text-neutral-400">{content.length} chars</span>
                )}
              </div>
              <textarea
                ref={textareaRef}
                value={content}
                onChange={(e) => setContent(e.target.value)}
                rows={11}
                placeholder={category ? "Content load ho raha hai…" : "Pehle category select karo…"}
                className="w-full rounded-lg border border-neutral-200 bg-neutral-50 px-3 py-2.5 font-mono text-[11px] leading-relaxed text-neutral-700 outline-none placeholder:text-neutral-300 focus:border-[#0b1f3a] focus:bg-white focus:ring-1 focus:ring-[#0b1f3a]/10"
              />
            </div>

            {/* Submit */}
            <button
              type="submit"
              disabled={!canCreate}
              className="flex h-10 w-full items-center justify-center gap-2 rounded-lg bg-[#0b1f3a] text-sm font-semibold text-white transition hover:bg-[#0d2444] active:bg-[#091a31] disabled:cursor-not-allowed disabled:bg-neutral-200 disabled:text-neutral-400"
            >
              {submitting ? (
                <>
                  <svg className="h-4 w-4 animate-spin" viewBox="0 0 24 24" fill="none">
                    <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="3" strokeOpacity="0.25"/>
                    <path d="M12 2a10 10 0 0 1 10 10" stroke="currentColor" strokeWidth="3" strokeLinecap="round"/>
                  </svg>
                  Saving…
                </>
              ) : (
                <>
                  <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none">
                    <path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
                  </svg>
                  Create template
                </>
              )}
            </button>
          </form>
        </div>

      </div>
    </AppShell>
  );
}
