import {
  DirectMessages,
  type DirectMessageThread,
} from "@/components/direct-messages";
import { Badge, MessageIcon, StatCard, UsersIcon } from "@/components/dashboard-ui";
import {
  formatPercent,
  getPropertyName,
  messageThreads,
  residents,
} from "@/lib/property-data-uk";

const contacts = [
  {
    name: "Jordan Avery",
    role: "Tenant",
    unit: "Whole house",
    target: "Reply by 11:30",
  },
  {
    name: "Maya Singh",
    role: "Move-in tenant",
    unit: "Apartment 7-02",
    target: "Today before 15:00",
  },
  {
    name: "Harper Nguyen",
    role: "Tenant",
    unit: "Flat 1-04",
    target: "Within 4 hours",
  },
  {
    name: "Sofia Bennett",
    role: "Tenant representative",
    unit: "Loft 2C",
    target: "Reply by end of day",
  },
  {
    name: "Camila Brooks",
    role: "Tenant",
    unit: "Flat 12A",
    target: "No SLA risk",
  },
];

function buildDirectThreads(): DirectMessageThread[] {
  return messageThreads.map((thread, index) => {
    const contact = contacts[index] ?? contacts[0];
    const propertyName = getPropertyName(thread.propertyId);

    return {
      id: thread.id,
      contactName: contact.name,
      contactRole: contact.role,
      propertyName,
      unit: contact.unit,
      subject: thread.title,
      channel: thread.channel,
      unread: thread.unread,
      sentiment: thread.sentiment,
      lastMessageAt: thread.lastMessageAt,
      responseTarget: contact.target,
      messages: [
        {
          id: `${thread.id}-system`,
          author: "PropertyPilot",
          body: `${thread.channel} conversation linked to ${propertyName}.`,
          sentAt: "2026-04-22T08:20:00",
          side: "system",
        },
        {
          id: `${thread.id}-tenant-1`,
          author: contact.name,
          body:
            thread.sentiment === "Needs attention"
              ? "Can someone come back to me on this today? A few neighbours are asking the same thing."
              : "Hi, could you confirm the next step when you get a moment?",
          sentAt: thread.lastMessageAt,
          side: "tenant",
        },
        {
          id: `${thread.id}-team-1`,
          author: "Property team",
          body:
            thread.sentiment === "Positive"
              ? "Thanks for flagging it. We have noted it and will keep the guidance updated."
              : "Thanks, we are checking this with the site team now and will update you shortly.",
          sentAt: "2026-04-22T09:58:00",
          side: "team",
        },
      ],
    };
  });
}

const directThreads = buildDirectThreads();
const unreadTotal = directThreads.reduce((sum, thread) => sum + thread.unread, 0);
const appPreferred = residents.filter((resident) =>
  resident.preferredChannel.includes("App"),
).length;

export default function CommunicationsPage() {
  return (
    <div className="space-y-6">
      <section className="flex flex-col gap-4 rounded-[30px] border border-border bg-surface px-5 py-5 md:flex-row md:items-end md:justify-between">
        <div>
          <p className="font-mono text-xs uppercase tracking-[0.3em] text-muted">
            Messages
          </p>
          <h1 className="mt-3 text-3xl font-semibold tracking-tight text-foreground">
            Direct messages
          </h1>
          <p className="mt-2 max-w-2xl text-sm leading-6 text-muted">
            One-to-one tenant conversations with context, quick actions, and a reply
            composer for the property team.
          </p>
        </div>
        <Badge tone={unreadTotal > 0 ? "amber" : "success"}>
          {unreadTotal} unread
        </Badge>
      </section>

      <section className="grid gap-4 md:grid-cols-3">
        <StatCard
          label="Direct threads"
          value={`${directThreads.length}`}
          hint="Active tenant conversations in the direct message inbox."
          change="1:1 inbox"
          tone="teal"
          icon={<MessageIcon />}
        />
        <StatCard
          label="Unread messages"
          value={`${unreadTotal}`}
          hint="Messages waiting for a manager response."
          change="Action needed"
          tone="amber"
        />
        <StatCard
          label="App-first tenants"
          value={`${formatPercent((appPreferred / residents.length) * 100, 0)}`}
          hint="Tenants who already prefer app-based messaging."
          change="Good adoption"
          tone="success"
          icon={<UsersIcon />}
        />
      </section>

      <DirectMessages threads={directThreads} />
    </div>
  );
}
