import { useEffect, useState } from "react";
import { MessageSquareQuote, Plus, Pencil, Trash2, Star, Save, X, Loader2 } from "lucide-react";
import CmsLayout from "./CmsLayout";
import { PageHeader } from "./ui";
import {
  fetchAllTestimonials,
  createTestimonial,
  updateTestimonial,
  deleteTestimonial,
  type ServiceTestimonial,
  type TestimonialInput,
} from "@/lib/testimonials";

const emptyForm: TestimonialInput = {
  name: "",
  company: "",
  role: "",
  quote: "",
  rating: 5,
  avatar_url: "",
  display_order: 10,
  is_active: true,
};

export default function CmsTestimonials() {
  const [items, setItems] = useState<ServiceTestimonial[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [form, setForm] = useState<TestimonialInput>(emptyForm);
  const [showForm, setShowForm] = useState(false);

  const load = async () => {
    setLoading(true);
    const rows = await fetchAllTestimonials();
    setItems(rows);
    setLoading(false);
  };

  useEffect(() => {
    load();
  }, []);

  const resetForm = () => {
    setForm(emptyForm);
    setEditingId(null);
    setShowForm(false);
  };

  const handleEdit = (t: ServiceTestimonial) => {
    setEditingId(t.id);
    setForm({
      name: t.name,
      company: t.company,
      role: t.role ?? "",
      quote: t.quote,
      rating: t.rating,
      avatar_url: t.avatar_url ?? "",
      display_order: t.display_order ?? 10,
      is_active: t.is_active ?? true,
    });
    setShowForm(true);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.name.trim() || !form.company.trim() || !form.quote.trim()) {
      alert("Name, company and quote are required.");
      return;
    }
    setSaving(true);
    const payload = { ...form, role: form.role || null, avatar_url: form.avatar_url || null };
    let result: ServiceTestimonial | null = null;
    if (editingId) {
      result = await updateTestimonial(editingId, payload);
    } else {
      result = await createTestimonial(payload);
    }
    setSaving(false);
    if (result) {
      await load();
      resetForm();
    } else {
      alert("Failed to save testimonial. Please try again.");
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm("Delete this testimonial? This cannot be undone.")) return;
    const ok = await deleteTestimonial(id);
    if (ok) await load();
    else alert("Failed to delete testimonial.");
  };

  return (
    <CmsLayout>
      <PageHeader
        icon={<MessageSquareQuote className="w-6 h-6" />}
        title="Service Testimonials"
        description="Manage customer testimonials displayed on the Service Catalog page."
      />

      {/* Add new button */}
      {!showForm && (
        <div className="mb-6">
          <button
            type="button"
            onClick={() => {
              setForm(emptyForm);
              setEditingId(null);
              setShowForm(true);
            }}
            className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-gradient-to-r from-[#0b6e3e] to-[#0a8048] text-white font-semibold shadow hover:shadow-lg transition"
          >
            <Plus className="w-4 h-4" /> Add Testimonial
          </button>
        </div>
      )}

      {/* Form */}
      {showForm && (
        <form
          onSubmit={handleSubmit}
          className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm mb-8"
        >
          <div className="flex items-center justify-between mb-5">
            <h3 className="text-lg font-bold text-slate-900">
              {editingId ? "Edit Testimonial" : "New Testimonial"}
            </h3>
            <button
              type="button"
              onClick={resetForm}
              className="text-slate-400 hover:text-slate-700"
              aria-label="Close form"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
          <div className="grid md:grid-cols-2 gap-4">
            <Field label="Name *">
              <input
                required
                value={form.name}
                onChange={(e) => setForm({ ...form, name: e.target.value })}
                className="input"
              />
            </Field>
            <Field label="Company *">
              <input
                required
                value={form.company}
                onChange={(e) => setForm({ ...form, company: e.target.value })}
                className="input"
              />
            </Field>
            <Field label="Role / Title">
              <input
                value={form.role ?? ""}
                onChange={(e) => setForm({ ...form, role: e.target.value })}
                className="input"
              />
            </Field>
            <Field label="Avatar / Logo URL">
              <input
                type="url"
                value={form.avatar_url ?? ""}
                onChange={(e) => setForm({ ...form, avatar_url: e.target.value })}
                placeholder="https://..."
                className="input"
              />
            </Field>
            <Field label="Rating (1-5)">
              <input
                type="number"
                min={1}
                max={5}
                value={form.rating}
                onChange={(e) =>
                  setForm({ ...form, rating: Math.max(1, Math.min(5, Number(e.target.value) || 5)) })
                }
                className="input"
              />
            </Field>
            <Field label="Display Order">
              <input
                type="number"
                value={form.display_order ?? 10}
                onChange={(e) =>
                  setForm({ ...form, display_order: Number(e.target.value) || 10 })
                }
                className="input"
              />
            </Field>
            <div className="md:col-span-2">
              <Field label="Quote *">
                <textarea
                  required
                  rows={4}
                  value={form.quote}
                  onChange={(e) => setForm({ ...form, quote: e.target.value })}
                  className="input resize-none"
                />
              </Field>
            </div>
            <div className="md:col-span-2 flex items-center gap-2">
              <input
                id="is_active"
                type="checkbox"
                checked={form.is_active ?? true}
                onChange={(e) => setForm({ ...form, is_active: e.target.checked })}
                className="w-4 h-4 rounded border-slate-300"
              />
              <label htmlFor="is_active" className="text-sm text-slate-700">
                Active (visible on public Service Catalog page)
              </label>
            </div>
          </div>
          <div className="mt-6 flex items-center gap-3">
            <button
              type="submit"
              disabled={saving}
              className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-gradient-to-r from-[#0b6e3e] to-[#0a8048] text-white font-semibold shadow hover:shadow-lg disabled:opacity-60 transition"
            >
              {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
              {editingId ? "Update" : "Create"}
            </button>
            <button
              type="button"
              onClick={resetForm}
              className="px-5 py-2.5 rounded-xl border border-slate-300 text-slate-700 font-semibold hover:bg-slate-50"
            >
              Cancel
            </button>
          </div>
        </form>
      )}

      {/* List */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-200 flex items-center justify-between">
          <div className="font-bold text-slate-900">All Testimonials</div>
          <div className="text-sm text-slate-500">{items.length} total</div>
        </div>
        {loading ? (
          <div className="p-10 text-center text-slate-500">
            <Loader2 className="w-5 h-5 animate-spin mx-auto mb-2" />
            Loading...
          </div>
        ) : items.length === 0 ? (
          <div className="p-10 text-center text-slate-500">
            No testimonials yet. Click "Add Testimonial" to create one.
          </div>
        ) : (
          <ul className="divide-y divide-slate-100">
            {items.map((t) => (
              <li key={t.id} className="p-5 flex items-start gap-4">
                <div className="w-14 h-14 rounded-xl bg-slate-100 flex items-center justify-center overflow-hidden shrink-0 border border-slate-200">
                  {t.avatar_url ? (
                    <img
                      src={t.avatar_url}
                      alt={t.company}
                      className="w-full h-full object-contain p-1"
                      onError={(e) => {
                        (e.currentTarget as HTMLImageElement).style.display = "none";
                      }}
                    />
                  ) : (
                    <span className="text-lg font-black text-slate-500">
                      {t.name.charAt(0)}
                    </span>
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap">
                    <div className="font-bold text-slate-900">{t.name}</div>
                    <div className="text-sm text-slate-500">
                      {t.role ? `${t.role} · ` : ""}
                      <span className="text-[#0b6e3e] font-semibold">{t.company}</span>
                    </div>
                    {!t.is_active && (
                      <span className="text-[10px] uppercase tracking-wider font-bold px-2 py-0.5 rounded-full bg-slate-200 text-slate-600">
                        Inactive
                      </span>
                    )}
                  </div>
                  <div className="flex items-center gap-1 mt-1">
                    {Array.from({ length: 5 }).map((_, i) => (
                      <Star
                        key={i}
                        className={`w-3.5 h-3.5 ${
                          i < t.rating ? "fill-amber-400 text-amber-400" : "text-slate-300"
                        }`}
                      />
                    ))}
                    <span className="ml-2 text-xs text-slate-400">
                      Order: {t.display_order ?? 10}
                    </span>
                  </div>
                  <p className="text-sm text-slate-600 mt-2 line-clamp-2">{t.quote}</p>
                </div>
                <div className="flex items-center gap-2 shrink-0">
                  <button
                    type="button"
                    onClick={() => handleEdit(t)}
                    className="p-2 rounded-lg text-slate-600 hover:text-[#0b6e3e] hover:bg-slate-100"
                    aria-label="Edit"
                  >
                    <Pencil className="w-4 h-4" />
                  </button>
                  <button
                    type="button"
                    onClick={() => handleDelete(t.id)}
                    className="p-2 rounded-lg text-slate-600 hover:text-red-600 hover:bg-red-50"
                    aria-label="Delete"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>

      <style>{`
        .input {
          width: 100%;
          padding: 0.625rem 0.875rem;
          border-radius: 0.75rem;
          border: 1px solid #cbd5e1;
          font-size: 0.875rem;
          color: #0f172a;
          background: #fff;
          outline: none;
          transition: border-color .15s, box-shadow .15s;
        }
        .input:focus {
          border-color: #0b6e3e;
          box-shadow: 0 0 0 3px rgba(11, 110, 62, 0.15);
        }
      `}</style>
    </CmsLayout>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <label className="block">
      <span className="block text-sm font-semibold text-slate-700 mb-1.5">{label}</span>
      {children}
    </label>
  );
}