'use client';

import React from 'react';
import { X } from 'lucide-react';

export type PitchPlayer = {
  playerId: string;
  name: string;
  role: string;
  teamShort: string;
  isTeamA: boolean;
  creditValue: number;
  photoUrl?: string;
  isCaptain?: boolean;
  isViceCaptain?: boolean;
};

type Props = {
  open: boolean;
  teamName: string;
  shortA: string;
  shortB: string;
  sideA: number;
  sideB: number;
  playersCount: number;
  creditsLeft: number;
  players: PitchPlayer[];
  onClose: () => void;
  footer?: React.ReactNode;
};

const ROLE_ROWS = [
  { key: 'WICKET_KEEPER', label: 'WICKET-KEEPERS' },
  { key: 'BATSMAN', label: 'BATTERS' },
  { key: 'ALL_ROUNDER', label: 'ALL-ROUNDERS' },
  { key: 'BOWLER', label: 'BOWLERS' },
] as const;

function initials(name: string) {
  const parts = name.trim().split(/\s+/);
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return `${parts[0][0] || ''}${parts[parts.length - 1][0] || ''}`.toUpperCase();
}

function Avatar({
  name,
  photoUrl,
  size = 'lg',
  badge,
}: {
  name: string;
  photoUrl?: string;
  size?: 'md' | 'lg';
  badge?: 'C' | 'VC' | null;
}) {
  const dim = size === 'lg' ? 'h-14 w-14 text-sm' : 'h-11 w-11 text-xs';
  return (
    <div className="relative mx-auto inline-flex">
      {badge && (
        <span
          className={`absolute -left-1 -top-1 z-10 flex h-5 min-w-5 items-center justify-center rounded-full px-1 text-[9px] font-extrabold shadow ${
            badge === 'C'
              ? 'bg-[var(--accent-primary)] text-white'
              : 'bg-amber-400 text-[var(--text-primary)]'
          }`}
          aria-label={badge === 'C' ? 'Captain' : 'Vice Captain'}
        >
          {badge}
        </span>
      )}
      {photoUrl ? (
        // eslint-disable-next-line @next/next/no-img-element
        <img
          src={photoUrl}
          alt=""
          className={`${dim} rounded-full border-2 border-white object-cover shadow-md`}
        />
      ) : (
        <span
          className={`${dim} flex items-center justify-center rounded-full border-2 border-white bg-[var(--bg-surface)] font-extrabold text-[var(--text-primary)] shadow-md`}
        >
          {initials(name)}
        </span>
      )}
    </div>
  );
}

export function TeamPitchPreview({
  open,
  teamName,
  shortA,
  shortB,
  sideA,
  sideB,
  playersCount,
  creditsLeft,
  players,
  onClose,
  footer,
}: Props) {
  if (!open) return null;

  return (
    <div
      className="fixed inset-0 z-[55] flex items-end justify-center bg-black/40 p-0 backdrop-blur-[1px] sm:items-center sm:p-4"
      role="dialog"
      aria-modal="true"
      aria-labelledby="team-preview-title"
      onClick={onClose}
    >
      <div
        className="flex max-h-[92dvh] w-full max-w-lg flex-col overflow-hidden rounded-t-2xl bg-[var(--bg-surface)] shadow-2xl sm:rounded-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="flex items-center justify-between border-b border-[var(--border-subtle)] px-4 py-3">
          <h2
            id="team-preview-title"
            className="font-display text-sm font-extrabold uppercase tracking-wide text-[var(--text-primary)]"
          >
            {teamName || 'My XI'}
          </h2>
          <button
            type="button"
            onClick={onClose}
            className="flex h-9 w-9 items-center justify-center rounded-full border border-[var(--border-subtle)] bg-[var(--bg-elevated)] text-[var(--text-secondary)]"
            aria-label="Close preview"
          >
            <X className="h-4 w-4" />
          </button>
        </header>

        <div className="flex items-center justify-between gap-2 border-b border-[var(--border-subtle)] bg-[var(--bg-elevated)] px-3 py-2.5 text-[11px] font-semibold text-[var(--text-secondary)]">
          <span>
            Players{' '}
            <span className="font-extrabold text-[var(--text-primary)]">
              {playersCount}/11
            </span>
          </span>
          <span className="text-center font-bold text-[var(--text-primary)]">
            {shortA} <span className="text-[var(--team-a)]">{sideA}</span>
            {' : '}
            <span className="text-[var(--team-b)]">{sideB}</span> {shortB}
          </span>
          <span>
            Credits Left{' '}
            <span className="font-extrabold text-[var(--accent-success)]">{creditsLeft}</span>
          </span>
        </div>

        <div className="d11-pitch flex-1 overflow-y-auto px-3 py-5">
          <div className="mx-auto max-w-md space-y-6">
            {ROLE_ROWS.map((row) => {
              const list = players.filter((p) => p.role === row.key);
              if (!list.length) return null;
              return (
                <section key={row.key}>
                  <p className="mb-3 text-center text-[10px] font-extrabold uppercase tracking-[0.2em] text-white/90">
                    {row.label}
                  </p>
                  <div className="flex flex-wrap items-start justify-center gap-x-5 gap-y-4">
                    {list.map((p) => (
                      <div key={p.playerId} className="w-[76px] text-center">
                        <Avatar
                          name={p.name}
                          photoUrl={p.photoUrl}
                          badge={p.isCaptain ? 'C' : p.isViceCaptain ? 'VC' : null}
                        />
                        <p
                          className={`mt-1.5 truncate rounded-md px-1.5 py-0.5 text-[10px] font-bold text-white shadow-sm ${
                            p.isTeamA ? 'bg-[var(--team-a)]' : 'bg-[var(--team-b)]'
                          }`}
                        >
                          {p.name.split(/\s+/).slice(-1)[0]}
                        </p>
                        <p className="mt-0.5 text-[10px] font-bold text-white/90">{p.creditValue}</p>
                      </div>
                    ))}
                  </div>
                </section>
              );
            })}
            {players.length === 0 && (
              <p className="rounded-xl bg-white/20 px-4 py-8 text-center text-sm font-semibold text-white">
                No players selected yet
              </p>
            )}
          </div>
        </div>

        {footer && (
          <div className="border-t border-[var(--border-subtle)] bg-[var(--bg-surface)] p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
            {footer}
          </div>
        )}
      </div>
    </div>
  );
}
