"use client";

import { getCatppuccinPrefixColor, getPrefixLabel } from "@/lib/types";
import { formatRelativeTime } from "@/lib/utils";

// ============================================================================
// Interfaces
// ============================================================================

export interface UserProfile {
  handle: string;
  avatar?: string;
  did?: string;

  // Stats
  assignedCount: number; // nodes currently assigned to this user
  closedCount: number; // nodes with status "closed" that are assigned to or created by this user
  claimedCount: number; // nodes this user has claimed
  commentCount: number; // total comments posted by this user
  likeCount: number; // total likes given by this user

  // Projects
  projects: {
    prefix: string;
    prefixLabel: string;
    color: string;
    count: number;
  }[];

  // Recent activity (already sorted newest-first, capped at 20)
  recentActivity: {
    type: "assigned" | "closed" | "commented" | "claimed" | "liked";
    nodeId: string;
    nodeTitle: string;
    time: string; // ISO 8601
    detail?: string; // comment preview, etc.
  }[];

  // Last active timestamp
  lastActiveAt?: string; // ISO 8601
}

interface ProfilePanelProps {
  isOpen: boolean;
  onClose: () => void;
  profile: UserProfile | null;
  onNodeNavigate: (nodeId: string) => void;
}

// ============================================================================
// Activity constants
// ============================================================================

const ACTIVITY_ICONS: Record<string, string> = {
  assigned: "📋",
  closed: "✅",
  commented: "💬",
  claimed: "🙋",
  liked: "❤️",
};

const ACTIVITY_VERBS: Record<string, string> = {
  assigned: "Assigned to",
  closed: "Closed",
  commented: "Commented on",
  claimed: "Claimed",
  liked: "Liked a comment on",
};

// ============================================================================
// ProfilePanel component
// ============================================================================

export function ProfilePanel({
  isOpen,
  onClose,
  profile,
  onNodeNavigate,
}: ProfilePanelProps) {
  return (
    <>
      {/* Desktop: right sidebar */}
      <aside
        className={`hidden md:flex absolute top-0 right-0 h-full w-[360px] bg-white dark:bg-zinc-900 border-l border-zinc-200 dark:border-zinc-700 flex-col shadow-xl dark:shadow-2xl dark:shadow-black/20 z-30 transform transition-transform duration-300 ease-out ${
          isOpen ? "translate-x-0" : "translate-x-full"
        }`}
      >
        <div className="flex items-center justify-between px-5 py-3 border-b border-zinc-100 dark:border-zinc-800 shrink-0">
          <h2 className="text-xs font-semibold text-zinc-400 dark:text-zinc-400 uppercase tracking-wider">
            Profile
          </h2>
          <button
            onClick={onClose}
            className="p-1 text-zinc-400 dark:text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 rounded-full hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
          >
            <svg
              className="w-4 h-4"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
              strokeWidth={2}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>
        <div className="flex-1 overflow-y-auto custom-scrollbar">
          {profile && (
            <ProfileContent profile={profile} onNodeNavigate={onNodeNavigate} />
          )}
        </div>
      </aside>

      {/* Mobile: bottom drawer */}
      <div
        className={`md:hidden fixed inset-x-0 bottom-0 transform transition-transform duration-300 ease-out z-20 ${
          isOpen ? "translate-y-0" : "translate-y-full"
        }`}
      >
        <div className="bg-white dark:bg-zinc-900 rounded-t-2xl shadow-2xl border-t border-zinc-200 dark:border-zinc-700 max-h-[70vh] flex flex-col">
          <div className="flex items-center justify-between px-5 py-3 border-b border-zinc-100 dark:border-zinc-800 shrink-0">
            <h2 className="text-xs font-semibold text-zinc-400 dark:text-zinc-400 uppercase tracking-wider">
              Profile
            </h2>
            <button
              onClick={onClose}
              className="p-1 text-zinc-400 dark:text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 rounded-full hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
            >
              <svg
                className="w-4 h-4"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            </button>
          </div>
          <div className="flex-1 overflow-y-auto custom-scrollbar">
            {profile && (
              <ProfileContent
                profile={profile}
                onNodeNavigate={onNodeNavigate}
              />
            )}
          </div>
        </div>
      </div>
    </>
  );
}

// ============================================================================
// ProfileContent — internal layout component
// ============================================================================

function ProfileContent({
  profile,
  onNodeNavigate,
}: {
  profile: UserProfile;
  onNodeNavigate: (nodeId: string) => void;
}) {
  // Check if user has zero activity
  const hasZeroActivity =
    profile.assignedCount === 0 &&
    profile.closedCount === 0 &&
    profile.claimedCount === 0 &&
    profile.commentCount === 0 &&
    profile.likeCount === 0 &&
    profile.projects.length === 0 &&
    profile.recentActivity.length === 0;

  return (
    <>
      {/* 1. Header — avatar + handle + last active */}
      <div className="px-5 pt-4 pb-3 border-b border-zinc-100 dark:border-zinc-800">
        <div className="flex items-center gap-3 mb-2">
          {/* Avatar: 48px circle */}
          {profile.avatar ? (
            <img
              src={profile.avatar}
              alt={profile.handle}
              className="w-12 h-12 rounded-full object-cover"
            />
          ) : (
            <div className="w-12 h-12 rounded-full bg-zinc-200 dark:bg-zinc-800 flex items-center justify-center text-zinc-500 dark:text-zinc-400 text-lg font-semibold">
              {profile.handle.charAt(0).toUpperCase()}
            </div>
          )}
          <div>
            <div className="text-sm font-semibold text-zinc-900 dark:text-zinc-100">
              {profile.handle}
            </div>
            {profile.lastActiveAt && (
              <div className="text-xs text-zinc-400 dark:text-zinc-400">
                Active {formatRelativeTime(profile.lastActiveAt)}
              </div>
            )}
          </div>
        </div>
      </div>

      {hasZeroActivity ? (
        <div className="flex flex-col items-center justify-center py-8 text-center">
          <p className="text-sm text-zinc-400 dark:text-zinc-500">No activity yet</p>
          <p className="text-xs text-zinc-300 dark:text-zinc-600 mt-1">
            This user hasn't contributed to any projects yet
          </p>
        </div>
      ) : (
        <>
          {/* 2. Stats grid — 2x2 grid of key metrics */}
          <div className="px-5 py-3 border-b border-zinc-100 dark:border-zinc-800">
            <div className="grid grid-cols-2 gap-3">
              <StatCard
                label="Assigned"
                value={profile.assignedCount}
                color="#1e66f5"
              />
              <StatCard
                label="Closed"
                value={profile.closedCount}
                color="#40a02b"
              />
              <StatCard
                label="Comments"
                value={profile.commentCount}
                color="#8839ef"
              />
              <StatCard
                label="Likes given"
                value={profile.likeCount}
                color="#ea76cb"
              />
            </div>
          </div>

          {/* 3. Projects section — list of projects with counts */}
          <div className="px-5 py-3 border-b border-zinc-100 dark:border-zinc-800">
            <h3 className="text-[11px] font-semibold text-zinc-400 dark:text-zinc-400 uppercase tracking-wider mb-2">
              Projects
            </h3>
            {profile.projects.length === 0 ? (
              <p className="text-xs text-zinc-400 dark:text-zinc-400 italic">No projects</p>
            ) : (
              <div className="flex flex-wrap gap-1.5">
                {profile.projects.map((p) => (
                  <span
                    key={p.prefix}
                    className="inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-[11px] font-medium"
                    style={{
                      backgroundColor: p.color + "15",
                      color: p.color,
                      border: `1px solid ${p.color}25`,
                    }}
                  >
                    <span
                      className="w-1.5 h-1.5 rounded-full"
                      style={{ backgroundColor: p.color }}
                    />
                    {p.prefixLabel}
                    <span className="text-zinc-400 font-normal">({p.count})</span>
                  </span>
                ))}
              </div>
            )}
          </div>

          {/* 4. Recent activity — chronological list */}
          <div className="px-5 py-3">
            <h3 className="text-[11px] font-semibold text-zinc-400 dark:text-zinc-400 uppercase tracking-wider mb-2">
              Recent Activity
            </h3>
            {profile.recentActivity.length === 0 ? (
              <p className="text-xs text-zinc-400 dark:text-zinc-400 italic">No activity</p>
            ) : (
              <div className="space-y-2">
                {profile.recentActivity.map((event, i) => (
                  <div key={i} className="flex items-start gap-2 text-xs">
                    <span className="mt-0.5">{ACTIVITY_ICONS[event.type]}</span>
                    <div className="flex-1 min-w-0">
                      <span className="text-zinc-600 dark:text-zinc-400">
                        {ACTIVITY_VERBS[event.type]}{" "}
                        <button
                          onClick={() => onNodeNavigate(event.nodeId)}
                          className="font-mono text-emerald-600 dark:text-emerald-400 hover:text-emerald-700 dark:hover:text-emerald-300 hover:underline"
                        >
                          {event.nodeId}
                        </button>
                      </span>
                      {event.detail && (
                        <p className="text-zinc-400 dark:text-zinc-400 truncate mt-0.5">
                          {event.detail}
                        </p>
                      )}
                      <div className="text-zinc-300 dark:text-zinc-500 mt-0.5">
                        {formatRelativeTime(event.time)}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </>
      )}
    </>
  );
}

// ============================================================================
// StatCard — small internal component for stats grid
// ============================================================================

function StatCard({
  label,
  value,
  color,
}: {
  label: string;
  value: number;
  color: string;
}) {
  return (
    <div className="bg-zinc-50 dark:bg-zinc-800 rounded-lg px-3 py-2">
      <div className="text-lg font-semibold" style={{ color }}>
        {value}
      </div>
      <div className="text-[11px] text-zinc-400 dark:text-zinc-400">{label}</div>
    </div>
  );
}
