"use client";

import { useEffect, useState } from "react";

type Message = {
  id: number;
  subject: string;
  bodyText: string;
  fromAddress: string;
  sentAt: string;
};

type UnassignedContact = {
  id: number;
  email: string;
  name: string | null;
  company: string | null;
  createdAt: string;
  messages: Message[];
};

export default function UnassignedPage() {
  const [items, setItems] = useState<UnassignedContact[] | null>(null);
  const [busyId, setBusyId] = useState<number | null>(null);

  useEffect(() => {
    fetch("/api/unassigned")
      .then((r) => r.json())
      .then(setItems);
  }, []);

  async function approve(id: number) {
    setBusyId(id);
    try {
      const res = await fetch(`/api/contacts/${id}/approve`, {
        method: "POST",
        headers: { "X-Midhub-Crm": "1" },
      });
      if (!res.ok) throw new Error();
      setItems((prev) => (prev ? prev.filter((i) => i.id !== id) : prev));
    } catch {
      alert("Couldn't approve. Try again.");
    } finally {
      setBusyId(null);
    }
  }

  async function ignore(id: number) {
    setBusyId(id);
    try {
      const res = await fetch(`/api/contacts/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json", "X-Midhub-Crm": "1" },
        body: JSON.stringify({ status: "ARCHIVED" }),
      });
      if (!res.ok) throw new Error();
      setItems((prev) => (prev ? prev.filter((i) => i.id !== id) : prev));
    } catch {
      alert("Couldn't ignore. Try again.");
    } finally {
      setBusyId(null);
    }
  }

  if (items === null) {
    return <p className="text-slate text-sm">Loading...</p>;
  }

  return (
    <div>
      <h1 className="font-heading font-600 text-2xl mb-1">Unassigned</h1>
      <p className="text-slate text-sm mb-6">
        New senders to info@ that aren't in your contacts yet. Approve to add them as a contact,
        or ignore if it's not relevant (vendor mail, spam, etc). Ignoring archives it rather than
        deleting — you can still find it later if needed.
      </p>

      {items.length === 0 && (
        <div className="border border-dashed border-black/15 rounded-lg p-10 text-center text-slate">
          Nothing waiting for review.
        </div>
      )}

      <div className="space-y-4">
        {items.map((item) => {
          const firstMessage = item.messages[0];
          return (
            <div key={item.id} className="border border-black/10 rounded-lg bg-white p-5">
              <div className="flex items-start justify-between mb-3">
                <div>
                  <div className="font-medium">{item.name || item.email}</div>
                  <div className="text-sm text-slate">{item.email}</div>
                  {item.company && <div className="text-sm text-slate">{item.company}</div>}
                </div>
                <div className="flex gap-2">
                  <button
                    disabled={busyId === item.id}
                    onClick={() => approve(item.id)}
                    className="bg-hub-green text-white px-3 py-1.5 rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50"
                  >
                    Approve
                  </button>
                  <button
                    disabled={busyId === item.id}
                    onClick={() => ignore(item.id)}
                    className="border border-black/15 text-slate px-3 py-1.5 rounded-md text-sm font-medium hover:bg-black/[.03] disabled:opacity-50"
                  >
                    Ignore
                  </button>
                </div>
              </div>
              {firstMessage && (
                <div className="border-t border-black/5 pt-3 mt-1">
                  <div className="text-sm font-medium mb-1">{firstMessage.subject}</div>
                  <p className="text-sm text-slate whitespace-pre-line line-clamp-4">
                    {firstMessage.bodyText}
                  </p>
                  {item.messages.length > 1 && (
                    <p className="text-xs text-slate mt-2">
                      +{item.messages.length - 1} more message{item.messages.length - 1 === 1 ? "" : "s"}
                    </p>
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}
