'use client';

import { MessageCircle, Search } from 'lucide-react';
import {
  Conversation,
  getConversationSubtitle,
  getConversationTitle,
} from '@/lib/messages';
import { JOBS_FEATURE_ENABLED } from '@/lib/features';
import { cn } from '@/lib/utils';

export type InboxFilter = 'all' | 'unread';

function inboxCopy(role: 'customer' | 'worker') {
  if (!JOBS_FEATURE_ENABLED) {
    return role === 'worker'
      ? {
          subtitle: 'Chats with customers who reach out to hire you.',
          empty: 'When a customer messages you from your profile, it will show up here.',
          placeholder: 'Select a conversation',
          placeholderBody:
            'Pick a chat from the list to reply. Customers message you from your public profile.',
        }
      : {
          subtitle: 'Chats with workers you contact from the directory.',
          empty: 'Open a worker profile and tap Message to start a conversation.',
          placeholder: 'Select a conversation',
          placeholderBody: 'Pick a chat from the list to continue messaging a worker.',
        };
  }

  return role === 'worker'
    ? {
        subtitle: 'Chats with customers about jobs and quotes.',
        empty: 'When a customer messages you about a job, the conversation will show up here.',
        placeholder: 'Select a conversation',
        placeholderBody:
          'Pick a chat from the list to reply, or browse available jobs to find new work.',
      }
    : {
        subtitle: 'Chats with workers about your jobs and quotes.',
        empty: 'Message a worker from a job posting or quotation to start a conversation.',
        placeholder: 'Select a conversation',
        placeholderBody: 'Pick a chat from the list to continue messaging about a job.',
      };
}

export function MessagesInboxHeader({
  role,
  search,
  onSearchChange,
  filter,
  onFilterChange,
  totalCount,
  unreadTotal,
}: {
  role: 'customer' | 'worker';
  search: string;
  onSearchChange: (value: string) => void;
  filter: InboxFilter;
  onFilterChange: (value: InboxFilter) => void;
  totalCount: number;
  unreadTotal: number;
}) {
  const copy = inboxCopy(role);

  return (
    <header className="shrink-0 border-b border-[#e2ddd2] bg-[#fffdf9]">
      <div className="space-y-3 px-4 pb-3 pt-4">
        <div className="flex items-start justify-between gap-3">
          <div className="min-w-0">
            <p className="text-[10px] font-semibold uppercase tracking-[0.14em] text-[var(--home-amber)]">
              Inbox
            </p>
            <h2 className="home-display mt-0.5 text-xl font-bold text-[var(--home-ink)]">
              Messages
            </h2>
            <p className="mt-1 text-sm leading-snug text-muted">{copy.subtitle}</p>
          </div>
          {totalCount > 0 ? (
            <div className="shrink-0 border border-[#e2ddd2] bg-white px-2.5 py-1.5 text-right">
              <p className="text-sm font-bold tabular-nums text-[var(--home-ink)]">{totalCount}</p>
              <p className="text-[10px] font-medium text-muted">
                {unreadTotal > 0 ? `${unreadTotal} unread` : 'All read'}
              </p>
            </div>
          ) : null}
        </div>

        <div className="relative">
          <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
          <input
            type="search"
            value={search}
            onChange={(e) => onSearchChange(e.target.value)}
            placeholder="Search by name…"
            className="h-10 w-full border border-[#e2ddd2] bg-white pl-9 pr-3 text-sm text-slate-900 placeholder:text-slate-400 focus:border-[var(--home-amber)] focus:outline-none focus:ring-2 focus:ring-[var(--home-amber)]/20"
          />
        </div>
      </div>

      <div className="flex gap-0 border-t border-[#e2ddd2]">
        {(
          [
            { key: 'all' as const, label: 'All', count: totalCount },
            { key: 'unread' as const, label: 'Unread', count: unreadTotal },
          ] as const
        ).map((tab) => {
          const active = filter === tab.key;
          return (
            <button
              key={tab.key}
              type="button"
              onClick={() => onFilterChange(tab.key)}
              className={cn(
                'relative flex flex-1 items-center justify-center gap-2 px-3 py-2.5 text-sm font-semibold transition-colors',
                active
                  ? 'bg-white text-[var(--home-ink)]'
                  : 'bg-transparent text-muted hover:bg-white/70 hover:text-slate-800'
              )}
            >
              {tab.label}
              <span
                className={cn(
                  'min-w-[1.25rem] px-1.5 py-0.5 text-center text-[10px] font-bold tabular-nums',
                  active
                    ? 'bg-[var(--home-ink)] text-white'
                    : 'bg-[#efeae0] text-slate-600'
                )}
              >
                {tab.count}
              </span>
              {active ? (
                <span className="absolute inset-x-0 bottom-0 h-0.5 bg-[var(--home-amber)]" />
              ) : null}
            </button>
          );
        })}
      </div>
    </header>
  );
}

export function MessagesSelectPrompt({ role }: { role: 'customer' | 'worker' }) {
  const copy = inboxCopy(role);

  return (
    <div className="flex flex-1 flex-col items-center justify-center bg-[var(--home-sand)]/40 px-8 text-center">
      <div className="mb-4 flex h-16 w-16 items-center justify-center bg-[var(--home-ink)] text-white">
        <MessageCircle className="h-8 w-8" />
      </div>
      <h3 className="home-display text-xl font-bold text-[var(--home-ink)]">{copy.placeholder}</h3>
      <p className="mt-2 max-w-sm text-sm leading-relaxed text-muted">{copy.placeholderBody}</p>
    </div>
  );
}

export function getMessagesEmptyCopy(role: 'customer' | 'worker') {
  return inboxCopy(role).empty;
}

export function filterConversations(
  conversations: Conversation[],
  search: string,
  currentUserId: string,
  inboxFilter: InboxFilter = 'all'
) {
  let list = conversations;
  if (inboxFilter === 'unread') {
    list = list.filter((c) => (c.unreadCount ?? 0) > 0);
  }

  const q = search.trim().toLowerCase();
  if (!q) return list;

  return list.filter((conversation) => {
    const title = getConversationTitle(conversation, currentUserId).toLowerCase();
    const subtitle = getConversationSubtitle(conversation).toLowerCase();
    const last = conversation.messages[0]?.content.toLowerCase() ?? '';
    return title.includes(q) || subtitle.includes(q) || last.includes(q);
  });
}
