"use client";

import { useState, useEffect, useMemo } from "react";
import {
  Plus,
  Trash2,
  AlertTriangle,
  Info,
  AlertOctagon,
  CheckCircle,
  Eye,
  ShieldCheck,
  RefreshCcw,
  Clock,
} from "lucide-react";

interface SystemMessage {
  id: string;
  type: "info" | "warning" | "error" | "maintenance";
  title: string | null;
  message: string;
  isActive: boolean;
  createdAt: string;
  expiresAt: string | null;
  _count: {
    views: number;
  };
}

interface User {
  id: string;
  role: string;
}

const TYPE_META = {
  info: {
    label: "Info",
    icon: Info,
    badge: "bg-blue-50 text-blue-700 border border-blue-200",
    accent: "from-blue-500/10 via-blue-500/5 to-white",
    dot: "bg-blue-500",
  },
  warning: {
    label: "Warning",
    icon: AlertTriangle,
    badge: "bg-amber-50 text-amber-700 border border-amber-200",
    accent: "from-amber-500/15 via-amber-500/8 to-white",
    dot: "bg-amber-500",
  },
  error: {
    label: "Error",
    icon: AlertOctagon,
    badge: "bg-red-50 text-red-700 border border-red-200",
    accent: "from-red-500/15 via-red-500/8 to-white",
    dot: "bg-red-500",
  },
  maintenance: {
    label: "Maintenance",
    icon: AlertTriangle,
    badge: "bg-purple-50 text-purple-700 border border-purple-200",
    accent: "from-purple-500/15 via-purple-500/8 to-white",
    dot: "bg-purple-500",
  },
} as const;

export default function SystemMessagesManager({ user }: { user: User }) {
  const [messages, setMessages] = useState<SystemMessage[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isCreating, setIsCreating] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [formData, setFormData] = useState({
    type: "info",
    title: "",
    message: "",
    expiresInHours: "24",
  });

  const fetchMessages = async () => {
    try {
      const response = await fetch("/api/staff/system-messages", {
        credentials: "include",
      });
      if (response.ok) {
        const data = await response.json();
        setMessages(data);
        setError(null);
      } else {
        const maybeError = await response.json().catch(() => null);
        const message =
          response.status === 401
            ? "Session expired. Please refresh and sign in again."
            : maybeError?.error ||
              "Failed to load messages. Please try refreshing.";
        setError(message);
      }
    } catch (err) {
      console.error("Failed to fetch messages:", err);
      setError("Failed to load messages. Please try refreshing.");
    } finally {
      setLoading(false);
    }
  };

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

  const stats = useMemo(() => {
    const active = messages.filter((m) => m.isActive).length;
    const totalViews = messages.reduce(
      (sum, m) => sum + (m._count?.views || 0),
      0,
    );
    const expiringSoon = messages.filter((m) => {
      if (!m.expiresAt) return false;
      const hoursLeft =
        (new Date(m.expiresAt).getTime() - Date.now()) / (1000 * 60 * 60);
      return hoursLeft > 0 && hoursLeft <= 48;
    }).length;

    return { active, total: messages.length, totalViews, expiringSoon };
  }, [messages]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setSubmitting(true);

    try {
      const response = await fetch("/api/staff/system-messages", {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });

      if (response.ok) {
        setIsCreating(false);
        setFormData({
          type: "info",
          title: "",
          message: "",
          expiresInHours: "24",
        });
        fetchMessages();
      } else {
        const data = await response.json().catch(() => null);
        const message =
          response.status === 401
            ? "Session expired. Please refresh and sign in again."
            : data?.error || "Failed to create message";
        setError(message);
      }
    } catch (err) {
      console.error("Submit error:", err);
      setError("Network error. Please try again.");
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Are you sure you want to delete this message?")) return;
    setError(null);

    try {
      const response = await fetch(`/api/staff/system-messages?id=${id}`, {
        method: "DELETE",
        credentials: "include",
      });
      if (response.ok) {
        fetchMessages();
      } else {
        const data = await response.json().catch(() => null);
        const message =
          response.status === 401
            ? "Session expired. Please refresh and sign in again."
            : data?.error || "Failed to delete message";
        setError(message);
      }
    } catch (err) {
      setError("Failed to delete message");
    }
  };

  const formatDate = (value: string | null) => {
    if (!value) return "Indefinite";
    return new Intl.DateTimeFormat("en", {
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    }).format(new Date(value));
  };

  return (
    <div className="space-y-8">
      {error && (
        <div className="flex items-center justify-between rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-red-700">
          <p className="text-sm">{error}</p>
          <button
            onClick={() => setError(null)}
            className="text-red-500 hover:text-red-700"
          >
            <span className="sr-only">Dismiss</span>
            <svg
              className="h-4 w-4"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>
      )}

      {/* Controls + Stats */}
      <div className="flex flex-col gap-4 rounded-3xl border border-gray-100 bg-white p-5 shadow-sm lg:flex-row lg:items-center lg:justify-between">
        <div className="flex flex-wrap items-center gap-3">
          <span className="inline-flex items-center gap-2 rounded-full bg-emerald-50 px-3 py-1 text-[11px] font-semibold text-emerald-700">
            <ShieldCheck className="h-4 w-4" />
            Broadcasts
          </span>
          <span className="inline-flex items-center gap-2 rounded-full bg-white px-3 py-1 text-[11px] font-semibold text-gray-700 shadow-inner">
            Role
            <span className="rounded-full bg-gray-900 px-2 py-0.5 text-white">
              {user.role}
            </span>
          </span>
          <span className="inline-flex items-center gap-2 rounded-full bg-gray-100 px-3 py-1 text-[11px] font-semibold text-gray-700">
            <Clock className="h-4 w-4 text-gray-500" />
            {loading
              ? "Loading..."
              : `${stats.total} total / ${stats.active} active`}
          </span>
          {stats.expiringSoon > 0 && (
            <span className="inline-flex items-center gap-2 rounded-full bg-amber-50 px-3 py-1 text-[11px] font-semibold text-amber-700">
              <AlertTriangle className="h-4 w-4" />
              {stats.expiringSoon} expiring soon
            </span>
          )}
        </div>

        <div className="flex flex-wrap gap-2">
          <button
            onClick={fetchMessages}
            className="inline-flex items-center gap-2 rounded-xl border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-gray-700 transition hover:-translate-y-0.5 hover:border-brand-green/40 hover:text-brand-green"
          >
            <RefreshCcw className="h-4 w-4" />
            Refresh
          </button>
          <button
            onClick={() => {
              setError(null);
              setIsCreating(true);
            }}
            className="inline-flex items-center gap-2 rounded-xl bg-brand-ink px-4 py-2 text-sm font-semibold text-white shadow-lg transition hover:-translate-y-0.5 hover:bg-black"
          >
            <Plus className="h-4 w-4" />
            New message
          </button>
        </div>
      </div>

      {/* At-a-glance */}
      <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
        <div className="rounded-2xl border border-gray-100 bg-gradient-to-br from-emerald-50 via-white to-emerald-50/60 p-4 shadow-sm">
          <p className="text-xs font-semibold uppercase tracking-[0.18em] text-emerald-700">
            Active
          </p>
          <div className="mt-2 flex items-center gap-3">
            <span className="text-3xl font-bold text-brand-ink">
              {stats.active}
            </span>
            <span className="text-sm text-gray-600">live notices</span>
          </div>
        </div>
        <div className="rounded-2xl border border-gray-100 bg-gradient-to-br from-blue-50 via-white to-indigo-50 p-4 shadow-sm">
          <p className="text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">
            Total views
          </p>
          <div className="mt-2 flex items-center gap-3">
            <span className="text-3xl font-bold text-brand-ink">
              {stats.totalViews.toLocaleString()}
            </span>
            <span className="text-sm text-gray-600">all time</span>
          </div>
        </div>
        <div className="rounded-2xl border border-gray-100 bg-gradient-to-br from-amber-50 via-white to-orange-50 p-4 shadow-sm">
          <p className="text-xs font-semibold uppercase tracking-[0.18em] text-amber-700">
            Expiring soon
          </p>
          <div className="mt-2 flex items-center gap-3">
            <span className="text-3xl font-bold text-brand-ink">
              {stats.expiringSoon}
            </span>
            <span className="text-sm text-gray-600">within 48h</span>
          </div>
        </div>
      </div>

      {/* Messages List */}
      <div className="rounded-3xl border border-gray-100 bg-white shadow-lg">
        <div className="flex items-center justify-between border-b border-gray-100 px-6 py-4">
          <div>
            <p className="text-xs font-semibold uppercase tracking-[0.18em] text-gray-500">
              Messages
            </p>
            <h3 className="text-lg font-bold text-brand-ink">
              Live & scheduled notices
            </h3>
          </div>
          <div className="flex gap-2 text-xs font-semibold text-gray-500">
            {Object.entries(TYPE_META).map(([key, meta]) => (
              <span
                key={key}
                className={`inline-flex items-center gap-2 rounded-full px-2.5 py-1 ${meta.badge}`}
              >
                <span className={`h-2 w-2 rounded-full ${meta.dot}`} />
                {meta.label}
              </span>
            ))}
          </div>
        </div>

        {loading ? (
          <div className="p-10 text-center text-gray-500">Loading...</div>
        ) : messages.length === 0 ? (
          <div className="space-y-3 p-10 text-center">
            <div className="inline-flex h-12 w-12 items-center justify-center rounded-full bg-gray-50 text-gray-400">
              <Info className="h-6 w-6" />
            </div>
            <p className="text-sm font-semibold text-brand-ink">
              No active system messages
            </p>
            <p className="text-sm text-gray-500">
              Create a broadcast to keep users informed.
            </p>
          </div>
        ) : (
          <div className="grid grid-cols-1 gap-4 p-5 md:grid-cols-2">
            {messages.map((msg) => {
              const meta = TYPE_META[msg.type];
              const Icon = meta.icon;

              return (
                <div
                  key={msg.id}
                  className="group relative overflow-hidden rounded-2xl border border-gray-100 bg-white shadow-sm transition hover:-translate-y-1 hover:shadow-md"
                >
                  <div
                    className={`absolute inset-0 bg-gradient-to-br ${meta.accent} opacity-80`}
                  />
                  <div className="relative flex flex-col gap-4 p-5">
                    <div className="flex items-start justify-between gap-3">
                      <div className="flex items-center gap-2">
                        <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-white shadow-inner">
                          <Icon className="h-5 w-5 text-brand-ink" />
                        </div>
                        <div
                          className={`inline-flex items-center gap-2 rounded-full px-3 py-1 text-xs font-semibold ${meta.badge}`}
                        >
                          <span
                            className={`h-2 w-2 rounded-full ${meta.dot}`}
                          />
                          {meta.label}
                        </div>
                        {msg.isActive ? (
                          <span className="inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2.5 py-1 text-[11px] font-semibold text-emerald-700">
                            <CheckCircle className="h-4 w-4" />
                            Active
                          </span>
                        ) : (
                          <span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2.5 py-1 text-[11px] font-semibold text-gray-600">
                            Inactive
                          </span>
                        )}
                      </div>

                      <button
                        onClick={() => handleDelete(msg.id)}
                        className="rounded-lg p-2 text-gray-400 transition hover:bg-red-50 hover:text-red-600"
                        title="Delete"
                      >
                        <Trash2 className="h-5 w-5" />
                      </button>
                    </div>

                    <div className="space-y-1">
                      {msg.title && (
                        <h4 className="text-lg font-semibold text-brand-ink">
                          {msg.title}
                        </h4>
                      )}
                      <p className="text-sm leading-relaxed text-gray-700">
                        {msg.message}
                      </p>
                    </div>

                    <div className="flex flex-wrap items-center gap-3 text-xs text-gray-600">
                      <div className="flex items-center gap-1">
                        <Eye className="h-4 w-4" />
                        {msg._count.views} views
                      </div>
                      <div>Created: {formatDate(msg.createdAt)}</div>
                      <div>Expires: {formatDate(msg.expiresAt)}</div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Create Modal */}
      {isCreating && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-slate-900/70 backdrop-blur-sm" />
          <div className="relative w-full max-w-2xl overflow-hidden rounded-3xl border border-gray-100 bg-white shadow-2xl">
            <div className="flex items-center justify-between border-b border-gray-100 bg-gradient-to-r from-brand-ink via-slate-900 to-slate-800 px-6 py-4 text-white">
              <div>
                <p className="text-xs font-semibold uppercase tracking-[0.18em] text-white/70">
                  New broadcast
                </p>
                <h3 className="text-lg font-bold">Create system message</h3>
              </div>
              <button
                onClick={() => setIsCreating(false)}
                className="rounded-full bg-white/10 px-3 py-1 text-xs font-semibold text-white transition hover:bg-white/20"
                type="button"
              >
                Cancel
              </button>
            </div>

            <form
              onSubmit={handleSubmit}
              className="grid gap-4 p-6 sm:grid-cols-2"
            >
              <div className="space-y-2">
                <label className="text-sm font-semibold text-brand-ink">
                  Type
                </label>
                <select
                  value={formData.type}
                  onChange={(e) =>
                    setFormData({ ...formData, type: e.target.value })
                  }
                  className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm shadow-inner focus:border-brand-green focus:ring-2 focus:ring-brand-green/30"
                >
                  <option value="info">Info</option>
                  <option value="warning">Warning</option>
                  <option value="error">Error</option>
                  <option value="maintenance">Maintenance</option>
                </select>
              </div>

              <div className="space-y-2">
                <label className="text-sm font-semibold text-brand-ink">
                  Duration
                </label>
                <select
                  value={formData.expiresInHours}
                  onChange={(e) =>
                    setFormData({ ...formData, expiresInHours: e.target.value })
                  }
                  className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm shadow-inner focus:border-brand-green focus:ring-2 focus:ring-brand-green/30"
                >
                  <option value="1">1 Hour</option>
                  <option value="24">24 Hours</option>
                  <option value="48">48 Hours</option>
                  <option value="168">1 Week</option>
                  <option value="0">Indefinite</option>
                </select>
              </div>

              <div className="sm:col-span-2 space-y-2">
                <label className="text-sm font-semibold text-brand-ink">
                  Title (optional)
                </label>
                <input
                  type="text"
                  value={formData.title}
                  onChange={(e) =>
                    setFormData({ ...formData, title: e.target.value })
                  }
                  className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm shadow-inner focus:border-brand-green focus:ring-2 focus:ring-brand-green/30"
                  placeholder="e.g., Scheduled maintenance"
                />
              </div>

              <div className="sm:col-span-2 space-y-2">
                <label className="text-sm font-semibold text-brand-ink">
                  Message
                </label>
                <textarea
                  required
                  value={formData.message}
                  onChange={(e) =>
                    setFormData({ ...formData, message: e.target.value })
                  }
                  className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm shadow-inner focus:border-brand-green focus:ring-2 focus:ring-brand-green/30"
                  rows={4}
                  placeholder="The message content..."
                />
              </div>

              <div className="sm:col-span-2 flex flex-col gap-3 sm:flex-row">
                <button
                  type="button"
                  onClick={() => setIsCreating(false)}
                  className="flex-1 rounded-xl border border-gray-200 px-4 py-3 text-sm font-semibold text-gray-700 transition hover:bg-gray-50"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={submitting}
                  className="flex-1 rounded-xl bg-brand-green px-4 py-3 text-sm font-semibold text-white shadow-lg transition hover:-translate-y-0.5 hover:bg-green-700 disabled:cursor-not-allowed disabled:opacity-80"
                >
                  {submitting ? "Publishing..." : "Publish message"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
