'use client';
import React, { useState } from 'react';
import { Avatar, Collapse, Empty, Segmented, Spin, Tag, Typography } from 'antd';
import { TrophyFilled } from '@ant-design/icons';
import Image from 'next/image';
import theme from '@/app/theme/themeConfig';
import { convertToShorthand } from '@/utills/helper';
import { useFeatureFlag } from '@/hooks/useFeatureFlag';
import { getMyTeamLeaderboard } from '../../leaderboard/service';
import { LeaderboardEntry, LeaderboardMetric, MyTeamLeaderboard } from '../../leaderboard/interface';

const { Panel } = Collapse;
const { Text } = Typography;

const PRIMARY_COLOR = theme.token?.colorPrimary || '#0E8744';
const MEDAL_COLORS = ['#D4A017', '#9AA0A6', '#B8703A'];

const MEDAL_OVERLAYS: { [rank: number]: string } = {
  1: '/images/gold-medal-overlay.png',
  2: '/images/silver-medal-overlay.png',
  3: '/images/bronze-medal-overlay.png',
};

const formatMoney = (value: number): string => `₹${convertToShorthand(value)}`;

const getInitials = (name: string): string => {
  const parts = (name || '').trim().split(/\s+/).filter(Boolean);
  if (!parts.length) {
    return '?';
  }
  return (parts[0][0] + (parts[1]?.[0] || '')).toUpperCase();
};

type AsyncStatus = 'idle' | 'loading' | 'succeeded' | 'failed';

const MedalPodium: React.FC = () => (
  <div
    style={{
      width: 60,
      height: 60,
      borderRadius: '50%',
      background: '#fff',
      border: `2px solid ${PRIMARY_COLOR}30`,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      flexShrink: 0,
      overflow: 'hidden',
      boxShadow: `0 2px 6px ${PRIMARY_COLOR}22`,
    }}
  >
    <Image
      src="/images/podiumimg.png"
      alt="Podium ranking"
      width={46}
      height={46}
      style={{ objectFit: 'contain' }}
    />
  </div>
);

const RankBadge: React.FC<{ rank: number; total: number }> = ({ rank, total }) => {
  const medalColor = rank <= 3 ? MEDAL_COLORS[rank - 1] : null;
  const overlaySrc = MEDAL_OVERLAYS[rank];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
      {overlaySrc ? (
        <div style={{ position: 'relative', width: 60, height: 60 }}>
          <div
            style={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              width: 32,
              height: 32,
              borderRadius: '50%',
              background: '#fff',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <Text strong style={{ color: medalColor as string, fontSize: 15 }}>{rank}</Text>
          </div>
          <Image
            src={overlaySrc}
            alt={`Rank ${rank} medal`}
            width={60}
            height={60}
            style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'contain', pointerEvents: 'none' }}
          />
        </div>
      ) : (
        <div
          style={{
            width: 60,
            height: 60,
            borderRadius: '50%',
            background: '#fff',
            border: `2.5px solid ${PRIMARY_COLOR}`,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            boxShadow: `0 2px 6px ${PRIMARY_COLOR}22`,
          }}
        >
          <Text strong style={{ color: PRIMARY_COLOR, fontSize: 20 }}>{rank}</Text>
        </div>
      )}
      <Text style={{ color: '#5c6470', fontSize: 10, fontWeight: 600, marginTop: 2 }}>
        of {total}
      </Text>
    </div>
  );
};

const CompactRow: React.FC<{ entry: LeaderboardEntry; metric: LeaderboardMetric; showCity: boolean }> = ({ entry, metric, showCity }) => {
  const medalColor = entry.rank <= 3 ? MEDAL_COLORS[entry.rank - 1] : null;
  const overlaySrc = MEDAL_OVERLAYS[entry.rank];
  const valueText = metric === 'visits'
    ? `${entry.visit_count} visit${entry.visit_count === 1 ? '' : 's'}`
    : formatMoney(entry.business_done);

  return (
    <div
      className="leaderboard-widget-row"
      style={{
        display: 'flex',
        alignItems: 'center',
        gap: 10,
        padding: '8px 10px',
        marginBottom: 4,
        borderRadius: 8,
        background: medalColor ? `${medalColor}12` : 'transparent',
        borderLeft: medalColor ? `3px solid ${medalColor}` : '3px solid transparent',
      }}
    >
      {overlaySrc ? (
        <div style={{ position: 'relative', width: 42, height: 42, flexShrink: 0 }}>
          <Avatar
            size={22}
            style={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              background: `${medalColor}22`,
              color: medalColor as string,
              fontSize: 10,
              fontWeight: 700,
            }}
          >
            {getInitials(entry.name)}
          </Avatar>
          <Image
            src={overlaySrc}
            alt={`Rank ${entry.rank} medal`}
            width={42}
            height={42}
            style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'contain', pointerEvents: 'none' }}
          />
        </div>
      ) : (
        <div style={{ position: 'relative', flexShrink: 0 }}>
          <Avatar
            size={26}
            style={{
              background: '#f0f0f0',
              color: '#6C6C6C',
              fontSize: 11,
              fontWeight: 700,
              border: '2px solid transparent',
            }}
          >
            {getInitials(entry.name)}
          </Avatar>
          <div
            style={{
              position: 'absolute',
              bottom: -3,
              right: -3,
              width: 14,
              height: 14,
              borderRadius: '50%',
              background: '#fff',
              color: '#9AA0A6',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: 8,
              fontWeight: 700,
              border: '1.5px solid #e8e8e8',
            }}
          >
            {entry.rank}
          </div>
        </div>
      )}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <Text
            strong={Boolean(medalColor)}
            ellipsis={{ tooltip: entry.name }}
            style={{ fontSize: 12, display: 'block' }}
          >
            {entry.name}
          </Text>
          {entry.is_team_lead && (
            <Tag color="blue" style={{ fontSize: 9, lineHeight: '12px', padding: '0 3px', margin: 0, flexShrink: 0 }}>
              TL
            </Tag>
          )}
        </div>
        {showCity && entry.city_name && (
          <Text type="secondary" style={{ fontSize: 10, display: 'block' }} ellipsis={{ tooltip: entry.city_name }}>
            {entry.city_name}
          </Text>
        )}
      </div>
      <div
        style={{
          flexShrink: 0,
          padding: '3px 8px',
          borderRadius: 12,
          background: `${PRIMARY_COLOR}12`,
        }}
      >
        <Text strong style={{ color: PRIMARY_COLOR, fontSize: 11.5, whiteSpace: 'nowrap' }}>
          {valueText}
        </Text>
      </div>
    </div>
  );
};

const LeaderboardAccordion: React.FC = () => {
  const leaderboardEnabled = useFeatureFlag('leaderboard');
  const [hasLoadedOnce, setHasLoadedOnce] = useState(false);
  const [status, setStatus] = useState<AsyncStatus>('idle');
  const [board, setBoard] = useState<MyTeamLeaderboard | null>(null);
  const [periodType, setPeriodType] = useState<'month' | 'year'>('month');
  const [scope, setScope] = useState<'city' | 'pan_india'>('city');

  const loadBoard = async(nextPeriodType: 'month' | 'year', nextScope: 'city' | 'pan_india') => {
    setStatus('loading');
    try {
      const res = await getMyTeamLeaderboard({ period: nextPeriodType, scope: nextScope });
      setBoard(res?.data?.data || null);
      setStatus('succeeded');
    } catch {
      setStatus('failed');
    }
  };

  const handleCollapseChange = (key: string | string[]) => {
    const isOpen = Array.isArray(key) ? key.length > 0 : Boolean(key);
    if (isOpen && !hasLoadedOnce) {
      setHasLoadedOnce(true);
      // eslint-disable-next-line @typescript-eslint/no-floating-promises
      loadBoard(periodType, scope);
    }
  };

  const handlePeriodChange = (value: 'month' | 'year') => {
    setPeriodType(value);
    // eslint-disable-next-line @typescript-eslint/no-floating-promises
    loadBoard(value, scope);
  };

  const handleScopeChange = (value: 'city' | 'pan_india') => {
    setScope(value);
    // eslint-disable-next-line @typescript-eslint/no-floating-promises
    loadBoard(periodType, value);
  };

  if (!leaderboardEnabled) {
    return null;
  }

  return (
    <div style={{ marginTop: 24 }}>
      <Collapse
        onChange={handleCollapseChange}
        className="dashboard-card leaderboard-widget-panel"
        bordered={false}
        style={{ background: '#FFF' }}
        expandIconPosition="end"
      >
        <Panel
          header={
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, position: 'relative', zIndex: 1 }}>
              <div
                style={{
                  width: 32,
                  height: 32,
                  borderRadius: '50%',
                  background: 'rgba(255,255,255,0.22)',
                  border: '1px solid rgba(255,255,255,0.35)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  flexShrink: 0,
                }}
              >
                <TrophyFilled style={{ color: '#FFD966', fontSize: 15 }} />
              </div>
              <Text strong style={{ fontSize: 15, color: '#fff' }}>Leaderboard</Text>
            </div>
          }
          key="leaderboard"
        >
          {hasLoadedOnce && (
            <Segmented
              block
              size="middle"
              className="leaderboard-tabs"
              value={periodType}
              onChange={(value) => handlePeriodChange(value as 'month' | 'year')}
              options={[
                { label: 'This Month', value: 'month' },
                { label: 'This FY', value: 'year' },
              ]}
              style={{ marginBottom: board?.is_scope_pickable ? 10 : 14 }}
            />
          )}
          {board?.is_scope_pickable && (
            <Segmented
              block
              size="middle"
              className="leaderboard-tabs"
              value={scope}
              onChange={(value) => handleScopeChange(value as 'city' | 'pan_india')}
              options={[
                { label: board.city_label || 'My City', value: 'city' },
                { label: 'Pan India', value: 'pan_india' },
              ]}
              style={{ marginBottom: 14 }}
            />
          )}
          <Spin spinning={status === 'loading'}>
            {status === 'failed' ? (
              <Text type="danger" style={{ display: 'block', margin: '16px 0' }}>
                Couldn&apos;t load this board — try again.
              </Text>
            ) : board ? (
              <>
                {board.my_rank && (
                  <div
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      flexWrap: 'wrap',
                      rowGap: 10,
                      gap: 16,
                      background: `linear-gradient(135deg, ${PRIMARY_COLOR}16, ${PRIMARY_COLOR}05)`,
                      border: `1px solid ${PRIMARY_COLOR}30`,
                      borderRadius: 12,
                      padding: '16px 18px',
                      marginBottom: 14,
                    }}
                  >
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
                      <MedalPodium />
                      <RankBadge rank={board.my_rank.rank} total={board.my_rank.total_participants} />
                    </div>
                    <div style={{ minWidth: 0 }}>
                      <Text
                        style={{
                          color: PRIMARY_COLOR,
                          display: 'block',
                          fontSize: 11,
                          fontWeight: 700,
                          letterSpacing: 0.5,
                          textTransform: 'uppercase',
                        }}
                      >
                        Your Position
                      </Text>
                      <Text strong style={{ fontSize: 14, display: 'block', marginTop: 2 }}>
                        {board.metric === 'visits'
                          ? `${board.my_rank.visit_count} visit${board.my_rank.visit_count === 1 ? '' : 's'}`
                          : (
                            <>
                              {board.my_rank.booking_count} booking{board.my_rank.booking_count === 1 ? '' : 's'} ·{' '}
                              {formatMoney(board.my_rank.business_done)}
                            </>
                          )}
                      </Text>
                    </div>
                  </div>
                )}

                {!board.rankings.length ? (
                  <Empty
                    description={`No ${board.metric === 'visits' ? 'visits' : 'bookings'} yet ${periodType === 'year' ? 'this FY' : 'this month'}`}
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    style={{ margin: '16px 0' }}
                  />
                ) : (
                  <div>
                    {board.rankings.map((entry) => (
                      <CompactRow
                        key={entry.user_id}
                        entry={entry}
                        metric={board.metric}
                        showCity={board.scope === 'pan_india'}
                      />
                    ))}
                  </div>
                )}
              </>
            ) : null}
          </Spin>
        </Panel>
      </Collapse>
    </div>
  );
};

export default LeaderboardAccordion;
