"use client";

import { useState } from "react";

import { Badge, MessageIcon } from "@/components/dashboard-ui";

export type DirectMessage = {
  id: string;
  author: string;
  body: string;
  sentAt: string;
  side: "tenant" | "team" | "system";
};

export type DirectMessageThread = {
  id: string;
  contactName: string;
  contactRole: string;
  propertyName: string;
  unit: string;
  subject: string;
  channel: string;
  unread: number;
  sentiment: "Positive" | "Neutral" | "Needs attention";
  lastMessageAt: string;
  responseTarget: string;
  messages: DirectMessage[];
};

type DirectMessagesProps = {
  threads: DirectMessageThread[];
};

function formatMessageTime(value: string) {
  const [, , month = "", day = ""] =
    value.match(/^(\d{4})-(\d{2})-(\d{2})/) ?? [];
  const [, hour = "00", minute = "00"] = value.match(/T(\d{2}):(\d{2})/) ?? [];
  const months: Record<string, string> = {
    "01": "Jan",
    "02": "Feb",
    "03": "Mar",
    "04": "Apr",
    "05": "May",
    "06": "Jun",
    "07": "Jul",
    "08": "Aug",
    "09": "Sept",
    "10": "Oct",
    "11": "Nov",
    "12": "Dec",
  };

  return `${Number(day)} ${months[month] ?? month}, ${hour}:${minute}`;
}

function getInitials(name: string) {
  return name
    .split(" ")
    .map((part) => part[0])
    .join("")
    .slice(0, 2)
    .toUpperCase();
}

export function DirectMessages({ threads }: DirectMessagesProps) {
  const [activeThreadId, setActiveThreadId] = useState(threads[0]?.id ?? "");
  const [drafts, setDrafts] = useState<Record<string, DirectMessage[]>>({});
  const [reply, setReply] = useState("");

  const activeThread = threads.find((thread) => thread.id === activeThreadId) ?? threads[0];

  if (!activeThread) {
    return null;
  }

  const conversation = [...activeThread.messages, ...(drafts[activeThread.id] ?? [])];
  const unreadTotal = threads.reduce((sum, thread) => sum + thread.unread, 0);

  function sendReply() {
    const trimmedReply = reply.trim();

    if (!trimmedReply) {
      return;
    }

    const message: DirectMessage = {
      id: `draft-${activeThread.id}-${Date.now()}`,
      author: "You",
      body: trimmedReply,
      sentAt: "2026-04-22T10:12:00",
      side: "team",
    };

    setDrafts((current) => ({
      ...current,
      [activeThread.id]: [...(current[activeThread.id] ?? []), message],
    }));
    setReply("");
  }

  return (
    <section className="grid min-h-[720px] gap-5 xl:grid-cols-[360px_minmax(0,1fr)]">
      <aside className="card-shell flex min-h-0 flex-col rounded-[30px] p-4">
        <div className="flex items-start justify-between gap-3 border-b border-border pb-4">
          <div>
            <p className="font-mono text-xs uppercase tracking-[0.28em] text-muted">
              Direct messages
            </p>
            <h2 className="mt-2 text-2xl font-semibold tracking-tight text-foreground">
              Tenant inbox
            </h2>
          </div>
          <Badge tone={unreadTotal > 0 ? "amber" : "success"}>
            {unreadTotal} unread
          </Badge>
        </div>

        <div className="mt-4 space-y-2 overflow-y-auto pr-1">
          {threads.map((thread) => {
            const active = thread.id === activeThread.id;

            return (
              <button
                className={[
                  "w-full rounded-[22px] border p-3 text-left transition",
                  active
                    ? "border-primary/35 bg-primary/10"
                    : "border-border bg-surface-strong hover:border-primary/30",
                ].join(" ")}
                key={thread.id}
                onClick={() => {
                  setActiveThreadId(thread.id);
                  setReply("");
                }}
                type="button"
              >
                <div className="flex items-start gap-3">
                  <span
                    className={[
                      "flex h-11 w-11 shrink-0 items-center justify-center rounded-full text-sm font-semibold",
                      active
                        ? "bg-primary text-white"
                        : "bg-surface-deep text-white",
                    ].join(" ")}
                  >
                    {getInitials(thread.contactName)}
                  </span>
                  <span className="min-w-0 flex-1">
                    <span className="flex items-center justify-between gap-2">
                      <span className="truncate font-semibold text-foreground">
                        {thread.contactName}
                      </span>
                      <span className="whitespace-nowrap text-xs text-muted">
                        {formatMessageTime(thread.lastMessageAt)}
                      </span>
                    </span>
                    <span className="mt-1 block truncate text-sm text-muted">
                      {thread.subject}
                    </span>
                    <span className="mt-2 flex items-center justify-between gap-2">
                      <span className="truncate text-xs text-muted">
                        {thread.propertyName} - {thread.unit}
                      </span>
                      {thread.unread > 0 ? (
                        <span className="rounded-full bg-accent px-2 py-0.5 text-xs font-semibold text-white">
                          {thread.unread}
                        </span>
                      ) : null}
                    </span>
                  </span>
                </div>
              </button>
            );
          })}
        </div>
      </aside>

      <div className="card-shell grid min-h-0 overflow-hidden rounded-[30px] xl:grid-cols-[minmax(0,1fr)_300px]">
        <div className="flex min-h-0 flex-col">
          <header className="border-b border-border bg-surface-strong px-5 py-4">
            <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
              <div className="flex items-center gap-3">
                <span className="flex h-12 w-12 items-center justify-center rounded-full bg-primary text-sm font-semibold text-white">
                  {getInitials(activeThread.contactName)}
                </span>
                <div>
                  <h2 className="text-xl font-semibold tracking-tight text-foreground">
                    {activeThread.contactName}
                  </h2>
                  <p className="text-sm text-muted">
                    {activeThread.contactRole} - {activeThread.propertyName}
                  </p>
                </div>
              </div>
              <div className="flex flex-wrap gap-2">
                <Badge tone="neutral">{activeThread.channel}</Badge>
                <Badge
                  tone={
                    activeThread.sentiment === "Needs attention"
                      ? "red"
                      : activeThread.sentiment === "Positive"
                        ? "success"
                        : "amber"
                  }
                >
                  {activeThread.sentiment}
                </Badge>
              </div>
            </div>
          </header>

          <div className="min-h-0 flex-1 space-y-4 overflow-y-auto px-5 py-5">
            {conversation.map((message) => {
              const teamMessage = message.side === "team";
              const systemMessage = message.side === "system";

              return (
                <div
                  className={[
                    "flex",
                    teamMessage ? "justify-end" : "justify-start",
                    systemMessage ? "justify-center" : "",
                  ].join(" ")}
                  key={message.id}
                >
                  <div
                    className={[
                      "max-w-[82%] rounded-[24px] px-4 py-3 text-sm leading-6",
                      teamMessage
                        ? "bg-primary text-white"
                        : systemMessage
                          ? "border border-border bg-surface-strong text-muted"
                          : "border border-border bg-surface-strong text-foreground",
                    ].join(" ")}
                  >
                    {!systemMessage ? (
                      <p
                        className={[
                          "mb-1 text-xs font-semibold",
                          teamMessage ? "text-white/72" : "text-muted",
                        ].join(" ")}
                      >
                        {message.author} - {formatMessageTime(message.sentAt)}
                      </p>
                    ) : null}
                    <p>{message.body}</p>
                  </div>
                </div>
              );
            })}
          </div>

          <footer className="border-t border-border bg-surface-strong p-4">
            <div className="rounded-[24px] border border-border bg-surface p-3">
              <textarea
                className="min-h-24 w-full resize-none bg-transparent text-sm leading-6 text-foreground outline-none placeholder:text-muted"
                onChange={(event) => setReply(event.target.value)}
                placeholder={`Reply to ${activeThread.contactName}...`}
                value={reply}
              />
              <div className="mt-3 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div className="flex flex-wrap gap-2">
                  <button className="rounded-full border border-border px-3 py-1.5 text-xs font-semibold text-muted transition hover:border-primary/30 hover:text-primary" type="button">
                    Attach file
                  </button>
                  <button className="rounded-full border border-border px-3 py-1.5 text-xs font-semibold text-muted transition hover:border-primary/30 hover:text-primary" type="button">
                    Add reminder
                  </button>
                </div>
                <button
                  className="inline-flex items-center justify-center gap-2 rounded-full border border-primary bg-primary px-5 py-2.5 text-sm font-semibold text-white transition hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50"
                  disabled={!reply.trim()}
                  onClick={sendReply}
                  type="button"
                >
                  <MessageIcon className="h-4 w-4" />
                  Send message
                </button>
              </div>
            </div>
          </footer>
        </div>

        <aside className="border-t border-border bg-surface-strong p-5 xl:border-l xl:border-t-0">
          <p className="font-mono text-xs uppercase tracking-[0.28em] text-muted">
            Contact details
          </p>
          <dl className="mt-5 space-y-4 text-sm">
            <div>
              <dt className="text-muted">Unit</dt>
              <dd className="mt-1 font-semibold text-foreground">{activeThread.unit}</dd>
            </div>
            <div>
              <dt className="text-muted">Property</dt>
              <dd className="mt-1 font-semibold text-foreground">
                {activeThread.propertyName}
              </dd>
            </div>
            <div>
              <dt className="text-muted">Response target</dt>
              <dd className="mt-1 font-semibold text-foreground">
                {activeThread.responseTarget}
              </dd>
            </div>
            <div>
              <dt className="text-muted">Latest message</dt>
              <dd className="mt-1 font-semibold text-foreground">
                {formatMessageTime(activeThread.lastMessageAt)}
              </dd>
            </div>
          </dl>

          <div className="mt-6 rounded-[22px] border border-border bg-surface p-4">
            <p className="text-sm font-semibold text-foreground">Quick actions</p>
            <div className="mt-3 grid gap-2">
              {[
                "Create repair job",
                "Book access slot",
                "Send rent statement",
                "Mark resolved",
              ].map((action) => (
                <button
                  className="rounded-full border border-border px-3 py-2 text-left text-xs font-semibold text-muted transition hover:border-primary/30 hover:text-primary"
                  key={action}
                  type="button"
                >
                  {action}
                </button>
              ))}
            </div>
          </div>
        </aside>
      </div>
    </section>
  );
}
