"use client";

import { useState, useEffect } from "react";
import { Loader2, Mail, MailOpen, Trash2, Circle } from "lucide-react";
import { formatDate } from "@/lib/types";

interface Message {
  id: string; name: string; email: string;
  subject: string | null; message: string;
  isRead: boolean; createdAt: string;
}

export default function AdminMessagesPage() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState<Message | null>(null);

  async function load() {
    const res = await fetch("/api/admin/messages");
    setMessages(await res.json());
    setLoading(false);
  }
  useEffect(() => { load(); }, []);

  async function markRead(id: string, isRead: boolean) {
    await fetch(`/api/admin/messages/${id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ isRead }),
    });
    setMessages((prev) => prev.map((m) => m.id === id ? { ...m, isRead } : m));
    if (selected?.id === id) setSelected((p) => p ? { ...p, isRead } : p);
  }

  async function handleDelete(id: string) {
    if (!confirm("پیام حذف شود؟")) return;
    await fetch(`/api/admin/messages/${id}`, { method: "DELETE" });
    setMessages((prev) => prev.filter((m) => m.id !== id));
    if (selected?.id === id) setSelected(null);
  }

  function handleSelect(msg: Message) {
    setSelected(msg);
    if (!msg.isRead) markRead(msg.id, true);
  }

  const unread = messages.filter((m) => !m.isRead).length;

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-text-primary">پیام‌ها</h1>
        {unread > 0 && <p className="text-sm text-accent mt-1">{unread} پیام خوانده‌نشده</p>}
      </div>

      {loading ? (
        <div className="flex justify-center py-20"><Loader2 className="animate-spin text-text-secondary" /></div>
      ) : messages.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-border py-20 text-center">
          <Mail size={32} className="text-text-secondary mb-3" />
          <p className="text-text-secondary">هنوز پیامی دریافت نشده</p>
        </div>
      ) : (
        <div className="grid gap-4 lg:grid-cols-[1fr_1.4fr]">
          {/* List */}
          <div className="space-y-2">
            {messages.map((msg) => (
              <button
                key={msg.id}
                onClick={() => handleSelect(msg)}
                className={`w-full rounded-xl border p-4 text-right transition-all hover:border-accent/30 ${selected?.id === msg.id ? "border-accent/40 bg-accent/5" : "border-border bg-surface"}`}
              >
                <div className="flex items-start gap-3">
                  <Circle size={8} className={`mt-2 shrink-0 ${!msg.isRead ? "fill-accent text-accent" : "fill-border text-border"}`} />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between gap-2">
                      <span className={`font-medium ${!msg.isRead ? "text-text-primary" : "text-text-secondary"}`}>{msg.name}</span>
                      <span className="font-mono text-xs text-text-secondary shrink-0">{formatDate(msg.createdAt, "fa")}</span>
                    </div>
                    <div className="mt-0.5 text-sm text-text-secondary truncate">{msg.subject ?? msg.message}</div>
                  </div>
                </div>
              </button>
            ))}
          </div>

          {/* Detail */}
          {selected ? (
            <div className="rounded-xl border border-border bg-surface p-6 space-y-4 h-fit">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <h2 className="text-lg font-semibold text-text-primary">{selected.subject ?? "(بدون موضوع)"}</h2>
                  <div className="mt-1 flex flex-wrap gap-3 text-sm text-text-secondary">
                    <span>{selected.name}</span>
                    <a href={`mailto:${selected.email}`} className="text-accent hover:underline">{selected.email}</a>
                  </div>
                  <div className="mt-1 font-mono text-xs text-text-secondary">{formatDate(selected.createdAt, "fa")}</div>
                </div>
                <div className="flex items-center gap-2 shrink-0">
                  <button onClick={() => markRead(selected.id, !selected.isRead)} title={selected.isRead ? "علامت‌گذاری به عنوان خوانده‌نشده" : "علامت‌گذاری به عنوان خوانده‌شده"} className="flex h-8 w-8 items-center justify-center rounded-lg border border-border text-text-secondary hover:border-accent/40 hover:text-accent transition-colors">
                    {selected.isRead ? <Mail size={14} /> : <MailOpen size={14} />}
                  </button>
                  <button onClick={() => handleDelete(selected.id)} className="flex h-8 w-8 items-center justify-center rounded-lg border border-border text-text-secondary hover:border-danger/40 hover:text-danger transition-colors">
                    <Trash2 size={14} />
                  </button>
                </div>
              </div>
              <div className="border-t border-border pt-4">
                <p className="text-text-primary leading-relaxed whitespace-pre-wrap">{selected.message}</p>
              </div>
              <a href={`mailto:${selected.email}?subject=Re: ${selected.subject ?? ""}`} className="inline-flex items-center gap-2 rounded-lg bg-accent/10 border border-accent/20 px-4 py-2 text-sm text-accent hover:bg-accent/20 transition-colors">
                <Mail size={14} /> پاسخ دادن
              </a>
            </div>
          ) : (
            <div className="hidden lg:flex items-center justify-center rounded-xl border border-dashed border-border h-64">
              <p className="text-sm text-text-secondary">یک پیام را انتخاب کنید</p>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
