import React, { useState } from "react";
import {
  Megaphone, Plus, Smartphone, MessageCircle, Bell, Trash2, X, Radio,
} from "lucide-react";
import { useLiveRows } from "../../shared/hooks/useLiveRows";
import { PageLoading } from "../../shared/components/PageLoading";

/* ---------------------------------------------------------------------- */
/*  DATA                                                                   */
/* ---------------------------------------------------------------------- */
const CHANNEL_ICON = { App: Bell, SMS: Smartphone, WhatsApp: MessageCircle };
const TYPES = ["Circular", "Notice", "Court Holiday", "Election Notification"];
const ALL_CHANNELS = ["App", "SMS", "WhatsApp"];

let noticeCounter = 100;
function genId() {
  noticeCounter += 1;
  return `NTC-${noticeCounter}`;
}
function today() {
  return new Date().toISOString().slice(0, 10);
}

const emptyForm = { title: "", type: TYPES[0], date: today(), channels: ["App"] };

function seedNotices() {
  return [
    { id: genId(), title: "Bar Association Annual Election Schedule Released", type: "Election Notification", date: "2026-06-20", channels: ["App", "SMS", "WhatsApp"], live: true },
    { id: genId(), title: "Court Holiday — Eid-ul-Adha", type: "Court Holiday", date: "2026-06-17", channels: ["App", "SMS"], live: true },
    { id: genId(), title: "Welfare Fund Application Deadline Extended", type: "Circular", date: "2026-06-10", channels: ["App", "WhatsApp"], live: true },
    { id: genId(), title: "New Chamber Allotment Notice", type: "Notice", date: "2026-06-05", channels: ["App"], live: false },
  ];
}

/* ---------------------------------------------------------------------- */
/*  SMALL UI                                                               */
/* ---------------------------------------------------------------------- */
function ChannelTag({ channel }) {
  const Icon = CHANNEL_ICON[channel];
  return (
    <span className="flex items-center gap-1 rounded-full bg-gray-100 border border-gray-200 px-2.5 py-1 text-[11px] text-gray-600">
      <Icon size={11} /> {channel}
    </span>
  );
}

function TypeBadge({ type }) {
  const colors = {
    "Circular": "bg-blue-50 text-blue-700 border-blue-200",
    "Notice": "bg-gray-100 text-gray-600 border-gray-200",
    "Court Holiday": "bg-amber-50 text-amber-700 border-amber-200",
    "Election Notification": "bg-red-50 text-red-600 border-red-200",
  };
  return (
    <span className={`text-[11px] font-medium px-2 py-0.5 rounded-full border ${colors[type] || "bg-gray-100 text-gray-500 border-gray-200"}`}>
      {type}
    </span>
  );
}

function PublishModal({ open, onClose, onPublish }) {
  const [form, setForm] = useState(emptyForm);

  if (!open) return null;

  const toggleChannel = (ch) =>
    setForm((prev) => ({
      ...prev,
      channels: prev.channels.includes(ch)
        ? prev.channels.filter((c) => c !== ch)
        : [...prev.channels, ch],
    }));

  const submit = (e) => {
    e.preventDefault();
    if (!form.title.trim() || form.channels.length === 0) return;
    onPublish({ ...form });
    setForm(emptyForm);
  };

  return (
    <div className="fixed inset-0 bg-gray-900/40 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg w-full max-w-md shadow-xl">
        <div className="flex items-center justify-between px-5 py-4 border-b border-gray-200">
          <h3 className="text-sm font-semibold text-gray-900 flex items-center gap-2">
            <Megaphone size={15} className="text-red-600" /> Publish Notice
          </h3>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600">
            <X size={16} />
          </button>
        </div>

        <form onSubmit={submit} className="p-5 space-y-4">
          <div>
            <label className="text-xs font-medium text-gray-500 mb-1 block">Title</label>
            <input
              required
              value={form.title}
              onChange={(e) => setForm({ ...form, title: e.target.value })}
              placeholder="e.g. Bar Election Schedule Released"
              className="w-full px-3 py-2 text-sm rounded-md border border-gray-200 bg-gray-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-red-200 focus:border-red-300"
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs font-medium text-gray-500 mb-1 block">Type</label>
              <select
                value={form.type}
                onChange={(e) => setForm({ ...form, type: e.target.value })}
                className="w-full px-3 py-2 text-sm rounded-md border border-gray-200 bg-gray-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-red-200 focus:border-red-300"
              >
                {TYPES.map((t) => <option key={t}>{t}</option>)}
              </select>
            </div>
            <div>
              <label className="text-xs font-medium text-gray-500 mb-1 block">Date</label>
              <input
                type="date"
                value={form.date}
                onChange={(e) => setForm({ ...form, date: e.target.value })}
                className="w-full px-3 py-2 text-sm rounded-md border border-gray-200 bg-gray-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-red-200 focus:border-red-300"
              />
            </div>
          </div>

          <div>
            <label className="text-xs font-medium text-gray-500 mb-1 block">Delivery Channels</label>
            <div className="flex gap-2">
              {ALL_CHANNELS.map((ch) => {
                const Icon = CHANNEL_ICON[ch];
                const active = form.channels.includes(ch);
                return (
                  <button
                    type="button"
                    key={ch}
                    onClick={() => toggleChannel(ch)}
                    className={`flex-1 flex items-center justify-center gap-1.5 rounded-md border px-3 py-2 text-xs font-medium transition-colors ${
                      active
                        ? "border-red-300 bg-red-50 text-red-600"
                        : "border-gray-200 text-gray-500 hover:border-gray-300"
                    }`}
                  >
                    <Icon size={13} /> {ch}
                  </button>
                );
              })}
            </div>
            {form.channels.length === 0 && (
              <p className="text-xs text-red-500 mt-1">Select at least one channel.</p>
            )}
          </div>

          <div className="flex items-center justify-end gap-2 pt-2 border-t border-gray-100">
            <button type="button" onClick={onClose} className="px-4 py-2 text-sm rounded-md text-gray-600 hover:bg-gray-100">
              Cancel
            </button>
            <button
              type="submit"
              disabled={form.channels.length === 0 || !form.title.trim()}
              className="px-4 py-2 text-sm rounded-md bg-red-600 text-white hover:bg-red-500 font-medium disabled:opacity-40 disabled:cursor-not-allowed"
            >
              Publish
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

/* ---------------------------------------------------------------------- */
/*  MAIN PAGE — standalone                                                 */
/* ---------------------------------------------------------------------- */
export default function NoticeBoard() {
  const { rows: notices, loading, add, update, remove } = useLiveRows('notices');
  const [showPublish, setShowPublish] = useState(false);
  const [toast, setToast] = useState("");

  const showToast = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(""), 2200);
  };

  const publish = async (form) => {
    try {
      await add({ ...form, live: true });
      showToast(`"${form.title}" published via ${form.channels.join(", ")}`);
      setShowPublish(false);
    } catch (err) {
      showToast(err?.message || 'Publish failed');
    }
  };

  const toggleLive = async (id) => {
    const n = notices.find((x) => x.id === id);
    if (!n) return;
    const next = !(n.live !== false);
    try {
      await update(id, { ...n, live: next });
      showToast(`"${n.title}" ${next ? "is live again" : "taken down"}`);
    } catch (err) {
      showToast(err?.message || 'Update failed');
    }
  };

  const deleteNotice = async (n) => {
    try {
      await remove(n.id);
      showToast(`"${n.title}" deleted`);
    } catch (err) {
      showToast(err?.message || 'Delete failed');
    }
  };

  const liveCount = notices.filter((n) => n.live !== false).length;

  if (loading) {
    return (
      <div className="w-full min-h-screen bg-gray-50">
        <PageLoading label="Loading notices…" />
      </div>
    );
  }

  return (
    <div className="w-full min-h-screen bg-gray-50 text-gray-900 p-6 space-y-5" style={{ fontFamily: "'IBM Plex Sans', 'Inter', sans-serif" }}>
      <style>{`@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600;700&display=swap');`}</style>

      {/* PAGE HEADER */}
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <p className="text-xs font-medium text-red-600 uppercase tracking-wide">Digital Notice Board</p>
          <h1 className="text-lg font-semibold text-gray-900 mt-0.5">Circulars &amp; Notifications</h1>
          <p className="text-xs text-gray-500 mt-1">
            Publish circulars, notices, court holidays, and election notifications — delivered via app push, SMS, and WhatsApp.
          </p>
        </div>
        <button
          onClick={() => setShowPublish(true)}
          className="flex items-center gap-2 px-4 py-2 text-sm rounded-md bg-red-600 text-white hover:bg-red-500 font-medium"
        >
          <Plus size={15} /> Publish Notice
        </button>
      </div>

      {/* STATS STRIP */}
      <section className="grid grid-cols-3 gap-4">
        {[
          { label: "Total Notices", value: notices.length },
          { label: "Live Now", value: liveCount, tone: "text-emerald-600" },
          { label: "Taken Down", value: notices.length - liveCount, tone: "text-gray-400" },
        ].map((s) => (
          <div key={s.label} className="bg-white border border-gray-200 rounded-lg p-4">
            <p className="text-xs font-medium text-gray-500 uppercase tracking-wide">{s.label}</p>
            <p className={`text-2xl font-semibold mt-1 ${s.tone || "text-gray-900"}`}>{s.value}</p>
          </div>
        ))}
      </section>

      {/* NOTICE LIST */}
      <section className="space-y-3">
        {notices.map((n) => (
          <div
            key={n.id}
            className={`bg-white border border-gray-200 rounded-lg p-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between transition-opacity ${
              n.live === false ? "opacity-50" : ""
            }`}
          >
            {/* Left */}
            <div className="flex items-start gap-3">
              <span className={`w-10 h-10 shrink-0 rounded-lg flex items-center justify-center ${n.live !== false ? "bg-red-50 text-red-600" : "bg-gray-100 text-gray-400"}`}>
                <Megaphone size={18} />
              </span>
              <div>
                <p className="text-sm font-semibold text-gray-900">{n.title}</p>
                <div className="flex items-center gap-2 mt-1 flex-wrap">
                  <TypeBadge type={n.type} />
                  <span className="text-[11px] text-gray-400">{n.date}</span>
                </div>
              </div>
            </div>

            {/* Right */}
            <div className="flex items-center gap-3 sm:shrink-0">
              {/* Channel tags */}
              <div className="flex items-center gap-1.5 flex-wrap">
                {n.channels.map((ch) => <ChannelTag key={ch} channel={ch} />)}
              </div>

              {/* Divider */}
              <div className="w-px h-6 bg-gray-200 shrink-0" />

              {/* Live toggle */}
              <button
                onClick={() => toggleLive(n.id)}
                className={`flex items-center gap-1.5 text-xs font-medium px-2.5 py-1.5 rounded-full border transition-colors ${
                  n.live !== false
                    ? "border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-100"
                    : "border-gray-200 bg-gray-50 text-gray-500 hover:bg-gray-100"
                }`}
              >
                <Radio size={11} className={n.live !== false ? "animate-pulse" : ""} />
                {n.live !== false ? "Live" : "Taken Down"}
              </button>

              {/* Delete */}
              <button
                onClick={() => deleteNotice(n)}
                className="rounded-md p-1.5 text-gray-400 hover:bg-red-50 hover:text-red-600"
              >
                <Trash2 size={14} />
              </button>
            </div>
          </div>
        ))}

        {notices.length === 0 && (
          <div className="bg-white border border-gray-200 rounded-lg p-10 text-center text-sm text-gray-400">
            No notices published yet.
          </div>
        )}
      </section>

      <PublishModal open={showPublish} onClose={() => setShowPublish(false)} onPublish={publish} />

      {toast && (
        <div className="fixed bottom-6 right-6 bg-gray-900 text-white text-sm px-4 py-2.5 rounded-md shadow-lg z-50">
          {toast}
        </div>
      )}
    </div>
  );
}