"use client";

import React, { useState } from "react";
import type { ChatRoom } from "./useChat";
import { theme, fontFamily } from "./theme";
import { smartTime } from "./chatHelpers";
import Avatar from "./Avatar";

interface Props {
  rooms: ChatRoom[];
  currentUserId: number;
  onSelectRoom: (room: ChatRoom) => void;
  onClose: () => void;
  isOnline: (userId: number) => boolean;
  onNewChat: () => void;
}

type Tab = "all" | "unread";

export default function ChatPanel({
  rooms,
  onSelectRoom,
  onClose,
  isOnline,
  onNewChat,
}: Props) {
  const [search, setSearch] = useState("");
  const [tab, setTab] = useState<Tab>("all");
  const [hoverId, setHoverId] = useState<number | null>(null);

  const totalUnread = rooms.reduce(
    (s, r) => s + Number(r.unread_count ?? 0),
    0,
  );

  const filtered = rooms.filter((r) => {
    const name =
      `${r.other_first_name ?? ""} ${r.other_last_name ?? ""} ${r.name ?? ""}`.toLowerCase();
    const matchSearch = name.includes(search.toLowerCase());
    const matchTab =
      tab === "all" || (tab === "unread" && Number(r.unread_count) > 0);
    return matchSearch && matchTab;
  });

  const onlineCount = rooms.filter(
    (r) => r.other_user_id && isOnline(r.other_user_id),
  ).length;

  return (
    <div
      className="qrs-chat-panel"
      style={{
        display: "flex",
        flexDirection: "column",
        height: "100%",
        backgroundColor: "#fff",
        fontFamily,
      }}
    >
      {/* ── Header (clean, professional) ── */}
      <div
        style={{
          padding: "20px 20px 16px",
          backgroundColor: "#fff",
          borderBottom: `1px solid ${theme.gray[100]}`,
          flexShrink: 0,
        }}
      >
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            marginBottom: 4,
          }}
        >
          <h2
            style={{
              margin: 0,
              fontWeight: 700,
              color: theme.gray[900],
              fontSize: 20,
              letterSpacing: "-0.02em",
            }}
          >
            Messages
          </h2>

          <div style={{ display: "flex", gap: 4 }}>
            <button
              onClick={onNewChat}
              aria-label="New conversation"
              title="New conversation"
              style={{
                background: "transparent",
                border: `1px solid ${theme.gray[200]}`,
                borderRadius: theme.radius.md,
                color: theme.gray[700],
                cursor: "pointer",
                width: 34,
                height: 34,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                transition: "all 0.15s",
                flexShrink: 0,
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.backgroundColor = theme.gray[50];
                e.currentTarget.style.borderColor = theme.gray[300];
                e.currentTarget.style.color = theme.brand[600];
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.backgroundColor = "transparent";
                e.currentTarget.style.borderColor = theme.gray[200];
                e.currentTarget.style.color = theme.gray[700];
              }}
            >
              <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.8"
                strokeLinecap="round"
                strokeLinejoin="round"
              >
                <path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7" />
                <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
              </svg>
            </button>
            <button
              onClick={onClose}
              aria-label="Close"
              style={{
                background: "transparent",
                border: "none",
                borderRadius: theme.radius.md,
                color: theme.gray[500],
                cursor: "pointer",
                padding: "8px 10px",
                fontSize: 18,
                fontWeight: 400,
                transition: "all 0.15s",
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.backgroundColor = theme.gray[100];
                e.currentTarget.style.color = theme.gray[900];
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.backgroundColor = "transparent";
                e.currentTarget.style.color = theme.gray[500];
              }}
            >
              ×
            </button>
          </div>
        </div>

        <div
          style={{
            fontSize: 13,
            color: theme.gray[500],
            marginBottom: 16,
            fontWeight: 500,
          }}
        >
          {onlineCount > 0 ? (
            <>
              <span
                style={{
                  display: "inline-block",
                  width: 6,
                  height: 6,
                  borderRadius: "50%",
                  backgroundColor: theme.success,
                  marginRight: 6,
                  verticalAlign: "middle",
                }}
              />
              {onlineCount} online · {rooms.length} conversation
              {rooms.length !== 1 ? "s" : ""}
            </>
          ) : (
            `${rooms.length} conversation${rooms.length !== 1 ? "s" : ""}`
          )}
        </div>

        {/* Search */}
        <div style={{ position: "relative" }}>
          <svg
            width="14"
            height="14"
            viewBox="0 0 24 24"
            fill="none"
            stroke={theme.gray[400]}
            strokeWidth="2.5"
            strokeLinecap="round"
            strokeLinejoin="round"
            style={{
              position: "absolute",
              left: 12,
              top: "50%",
              transform: "translateY(-50%)",
              pointerEvents: "none",
            }}
          >
            <circle cx="11" cy="11" r="8" />
            <line x1="21" y1="21" x2="16.65" y2="16.65" />
          </svg>
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search conversations"
            style={{
              width: "100%",
              padding: "10px 14px 10px 36px",
              borderRadius: theme.radius.md,
              border: `1.5px solid ${theme.gray[200]}`,
              outline: "none",
              fontSize: 13.5,
              backgroundColor: theme.gray[50],
              color: theme.gray[900],
              boxSizing: "border-box",
              fontFamily,
              transition: "all 0.15s",
            }}
            onFocus={(e) => {
              e.currentTarget.style.borderColor = theme.brand[500];
              e.currentTarget.style.backgroundColor = "#fff";
              e.currentTarget.style.boxShadow = `0 0 0 3px ${theme.brand[500]}20`;
            }}
            onBlur={(e) => {
              e.currentTarget.style.borderColor = theme.gray[200];
              e.currentTarget.style.backgroundColor = theme.gray[50];
              e.currentTarget.style.boxShadow = "none";
            }}
          />
        </div>
      </div>

      {/* ── Tabs ── */}
      <div
        style={{
          display: "flex",
          gap: 4,
          padding: "8px 16px",
          backgroundColor: "#fff",
          flexShrink: 0,
          borderBottom: `1px solid ${theme.gray[100]}`,
        }}
      >
        {(["all", "unread"] as Tab[]).map((t) => {
          const active = tab === t;
          const label =
            t === "all"
              ? "All"
              : `Unread${totalUnread > 0 ? ` · ${totalUnread}` : ""}`;
          return (
            <button
              key={t}
              onClick={() => setTab(t)}
              style={{
                padding: "6px 14px",
                border: "none",
                cursor: "pointer",
                fontSize: 13,
                fontWeight: active ? 600 : 500,
                color: active ? theme.brand[600] : theme.gray[600],
                backgroundColor: active ? theme.brand[50] : "transparent",
                borderRadius: theme.radius.md,
                transition: "all 0.15s",
                fontFamily,
              }}
            >
              {label}
            </button>
          );
        })}
      </div>

      {/* ── Room list ── */}
      <div style={{ flex: 1, overflowY: "auto", backgroundColor: "#fff" }}>
        {filtered.length === 0 ? (
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              justifyContent: "center",
              height: "100%",
              gap: 12,
              color: theme.gray[500],
              padding: 24,
            }}
          >
            <div
              style={{
                width: 56,
                height: 56,
                borderRadius: theme.radius.full,
                backgroundColor: theme.gray[100],
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <svg
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke={theme.gray[400]}
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              >
                {tab === "unread" ? (
                  <polyline points="20 6 9 17 4 12" />
                ) : (
                  <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
                )}
              </svg>
            </div>
            <div style={{ textAlign: "center" }}>
              <div
                style={{
                  fontSize: 14,
                  fontWeight: 600,
                  color: theme.gray[800],
                  marginBottom: 4,
                }}
              >
                {tab === "unread"
                  ? "You're all caught up"
                  : search
                    ? "No matches"
                    : "No conversations yet"}
              </div>
              <div style={{ fontSize: 12.5, color: theme.gray[500] }}>
                {tab === "unread"
                  ? "No unread messages"
                  : search
                    ? "Try a different search"
                    : 'Click "New" to start chatting'}
              </div>
            </div>
          </div>
        ) : (
          filtered.map((room) => {
            const otherName =
              `${room.other_first_name ?? ""} ${room.other_last_name ?? ""}`.trim() ||
              room.name ||
              "Chat";
            const isOnlineNow = room.other_user_id
              ? isOnline(room.other_user_id)
              : false;
            const unread = Number(room.unread_count ?? 0);
            const isHovered = hoverId === room.id;

            const lastMsg = room.last_message ?? "Start a conversation";

            return (
              <div
                key={room.id}
                onClick={() => onSelectRoom(room)}
                onMouseEnter={() => setHoverId(room.id)}
                onMouseLeave={() => setHoverId(null)}
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 12,
                  padding: "14px 16px",
                  cursor: "pointer",
                  backgroundColor: isHovered ? theme.gray[50] : "#fff",
                  transition: "background-color 0.15s",
                  position: "relative",
                }}
              >
                {unread > 0 && (
                  <div
                    style={{
                      position: "absolute",
                      left: 0,
                      top: 0,
                      bottom: 0,
                      width: 3,
                      backgroundColor: theme.brand[500],
                    }}
                  />
                )}

                <Avatar
                  name={otherName}
                  size={44}
                  status={isOnlineNow ? "online" : "offline"}
                />

                <div style={{ flex: 1, minWidth: 0 }}>
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "baseline",
                      marginBottom: 2,
                    }}
                  >
                    <span
                      style={{
                        fontWeight: unread > 0 ? 600 : 500,
                        fontSize: 14,
                        color: theme.gray[900],
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        whiteSpace: "nowrap",
                        letterSpacing: "-0.01em",
                      }}
                    >
                      {otherName}
                    </span>
                    <span
                      style={{
                        fontSize: 11.5,
                        flexShrink: 0,
                        marginLeft: 8,
                        color: unread > 0 ? theme.brand[600] : theme.gray[400],
                        fontWeight: unread > 0 ? 600 : 500,
                      }}
                    >
                      {smartTime(room.last_message_at)}
                    </span>
                  </div>

                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      gap: 8,
                    }}
                  >
                    <span
                      style={{
                        fontSize: 13,
                        color: unread > 0 ? theme.gray[700] : theme.gray[500],
                        fontWeight: unread > 0 ? 500 : 400,
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        whiteSpace: "nowrap",
                        flex: 1,
                      }}
                    >
                      {lastMsg}
                    </span>
                    {unread > 0 && (
                      <span
                        style={{
                          minWidth: 20,
                          height: 20,
                          borderRadius: theme.radius.full,
                          background: theme.gradient.brand,
                          color: "#fff",
                          fontSize: 11,
                          fontWeight: 700,
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          padding: "0 7px",
                          flexShrink: 0,
                          boxShadow: theme.shadow.sm,
                        }}
                      >
                        {unread > 99 ? "99+" : unread}
                      </span>
                    )}
                  </div>
                </div>
              </div>
            );
          })
        )}
      </div>
    </div>
  );
}
