'use client';
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import { AppDispatch, RootState } from '@/store/store';
import PageHeader from '@/components/pageHeader';
import { Avatar, Card, Empty, Segmented, Select, Spin, Tag, Typography } from 'antd';
import { TrophyFilled, TrophyOutlined } from '@ant-design/icons';
import Image from 'next/image';
import dayjs from 'dayjs';
import theme from '@/app/theme/themeConfig';
import { convertToShorthand } from '@/utills/helper';
import { useFeatureFlag } from '@/hooks/useFeatureFlag';
import { fetchLeaderboard, setPeriodType, setScope, setSelectedRoleId } from './slice';
import { LeaderboardEntry, LeaderboardMetric, LeaderboardMyRank, LeaderboardSection } from './interface';

const { Title, Text } = Typography;

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

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();
};

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

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 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 LeaderboardListRow: React.FC<{ entry: LeaderboardEntry; metric: LeaderboardMetric }> = ({ entry, metric }) => {
  const medalColor = entry.rank <= 3 ? MEDAL_COLORS[entry.rank - 1] : null;
  const overlaySrc = MEDAL_OVERLAYS[entry.rank];

  return (
    <div
      className={`leaderboard-page-row${entry.rank === 1 ? ' leaderboard-rank-one' : ''}`}
      style={{
        display: 'flex',
        alignItems: 'center',
        gap: 12,
        padding: '10px 12px',
        marginBottom: 6,
        borderRadius: 10,
        background: medalColor ? `${medalColor}1E` : entry.rank % 2 === 0 ? `${PRIMARY_COLOR}09` : 'transparent',
        border: medalColor ? `1px solid ${medalColor}55` : '1px solid transparent',
        borderLeft: medalColor ? `4px solid ${medalColor}` : '4px solid transparent',
      }}
    >
      {overlaySrc ? (
        <div style={{ position: 'relative', width: 52, height: 52, flexShrink: 0 }}>
          <Avatar
            size={28}
            style={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              background: `${medalColor}22`,
              color: medalColor as string,
              fontSize: 12,
              fontWeight: 700,
            }}
          >
            {getInitials(entry.name)}
          </Avatar>
          <Image
            src={overlaySrc}
            alt={`Rank ${entry.rank} medal`}
            width={52}
            height={52}
            style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'contain', pointerEvents: 'none' }}
          />
        </div>
      ) : (
        <>
          <div
            style={{
              width: 30,
              height: 30,
              borderRadius: '50%',
              background: `linear-gradient(135deg, ${PRIMARY_COLOR}28, ${PRIMARY_COLOR}0A)`,
              color: PRIMARY_COLOR,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontWeight: 700,
              fontSize: 12,
              flexShrink: 0,
              border: `1px solid ${PRIMARY_COLOR}30`,
            }}
          >
            {entry.rank}
          </div>
          <Avatar size={32} style={{ background: '#f0f0f0', color: '#6C6C6C', fontSize: 13, fontWeight: 700, flexShrink: 0 }}>
            {getInitials(entry.name)}
          </Avatar>
        </>
      )}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <Text strong={Boolean(medalColor)} ellipsis={{ tooltip: entry.name }} style={{ display: 'block', minWidth: 0 }}>
            {entry.name}
          </Text>
          {entry.is_team_lead && (
            <Tag color="blue" style={{ fontSize: 10, lineHeight: '14px', padding: '0 4px', margin: 0, flexShrink: 0 }}>
              TL
            </Tag>
          )}
        </div>
        {entry.city_name && (
          <Text style={{ fontSize: 11, display: 'block', color: '#6b7280', fontWeight: 500 }} ellipsis={{ tooltip: entry.city_name }}>
            {entry.city_name}
          </Text>
        )}
      </div>
      {metric === 'visits' ? (
        <div style={{ flexShrink: 0, padding: '4px 12px', borderRadius: 12, background: `${PRIMARY_COLOR}1E`, border: `1px solid ${PRIMARY_COLOR}40` }}>
          <Text strong style={{ color: PRIMARY_COLOR, fontSize: 12.5, whiteSpace: 'nowrap' }}>
            {entry.visit_count} visit{entry.visit_count === 1 ? '' : 's'}
          </Text>
        </div>
      ) : (
        <>
          <Text style={{ fontSize: 12, whiteSpace: 'nowrap', color: '#4b5563', fontWeight: 600 }}>
            {entry.booking_count} booking{entry.booking_count === 1 ? '' : 's'}
          </Text>
          <div style={{ flexShrink: 0, padding: '4px 12px', borderRadius: 12, background: `${PRIMARY_COLOR}1E`, border: `1px solid ${PRIMARY_COLOR}40` }}>
            <Text strong style={{ color: PRIMARY_COLOR, fontSize: 12.5, whiteSpace: 'nowrap' }}>
              {formatMoney(entry.business_done)}
            </Text>
          </div>
        </>
      )}
    </div>
  );
};

const LeaderboardSectionCard: React.FC<{ section: LeaderboardSection; myRank: LeaderboardMyRank | null }> = ({ section, myRank }) => {
  return (
    <Card
      style={{ borderRadius: 14, marginBottom: 24, overflow: 'hidden', boxShadow: '0 10px 30px rgba(14, 135, 68, 0.12)', border: 'none' }}
      bodyStyle={{ padding: 0 }}
    >
      <div
        className="leaderboard-header-banner"
        style={{
          position: 'relative',
          display: 'flex',
          alignItems: 'center',
          gap: 10,
          padding: '16px 20px',
          overflow: 'hidden',
          background: `linear-gradient(120deg, #14A360 0%, ${PRIMARY_COLOR} 55%, #0a5c30 100%)`,
        }}
      >
        <div
          style={{
            position: 'absolute',
            top: '-60%',
            right: '-8%',
            width: '55%',
            height: '220%',
            background: 'radial-gradient(circle, rgba(255,255,255,0.22) 0%, rgba(255,255,255,0) 70%)',
            pointerEvents: 'none',
          }}
        />
        <TrophyFilled style={{ color: '#FFD966', fontSize: 19, position: 'relative' }} />
        <Title level={5} style={{ margin: 0, color: '#fff', position: 'relative' }}>
          {section.role_label}
        </Title>
        <span
          style={{
            position: 'relative',
            marginLeft: 2,
            padding: '3px 12px',
            borderRadius: 20,
            fontSize: 12,
            fontWeight: 700,
            color: '#5c3d00',
            background: 'linear-gradient(135deg, #FFE9A8, #FFC94A)',
            boxShadow: '0 2px 6px rgba(255, 201, 74, 0.5)',
          }}
        >
          Top {section.limit}
        </span>
      </div>

      <div style={{ padding: 20 }}>
        {myRank && (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 14,
              flexWrap: 'wrap',
              rowGap: 6,
              background: `linear-gradient(135deg, ${PRIMARY_COLOR}22, ${PRIMARY_COLOR}08)`,
              border: `1.5px solid ${PRIMARY_COLOR}45`,
              borderRadius: 12,
              padding: '12px 18px',
              marginBottom: 20,
              boxShadow: `0 4px 14px ${PRIMARY_COLOR}18`,
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
              <MedalPodium />
              <RankBadge rank={myRank.rank} total={myRank.total_participants} />
            </div>
            <div style={{ minWidth: 0 }}>
              <Text strong style={{ fontSize: 15, display: 'block', marginTop: 2, color: '#1a1a1a' }}>
                {section.metric === 'visits'
                  ? `${myRank.visit_count} visit${myRank.visit_count === 1 ? '' : 's'}`
                  : (
                    <>
                      {myRank.booking_count} booking{myRank.booking_count === 1 ? '' : 's'} ·{' '}
                      {formatMoney(myRank.business_done)}
                    </>
                  )}
              </Text>
            </div>
          </div>
        )}

        {section.rankings.length > 0 && (
          <div>
            {section.rankings.map((entry) => (
              <LeaderboardListRow key={entry.user_id} entry={entry} metric={section.metric} />
            ))}
          </div>
        )}
      </div>
    </Card>
  );
};

const LeaderboardPage: React.FC = () => {
  const dispatch: AppDispatch = useDispatch();
  const router = useRouter();
  const { data: session } = useSession();
  const leaderboardEnabled = useFeatureFlag('leaderboard');
  const { periodType, scope, selectedRoleId, availableRoles, section, cityLabel, myRank, status, period } = useSelector(
    (state: RootState) => state.leaderboard
  );

  useEffect(() => {
    if (session === null || !leaderboardEnabled) {
      router.replace('/permission-denied');
    }
  }, [leaderboardEnabled, session, router]);

  useEffect(() => {
    dispatch(fetchLeaderboard());
  }, []);

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

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

  const handleRoleChange = (value: number) => {
    dispatch(setSelectedRoleId(value));
    // eslint-disable-next-line @typescript-eslint/no-floating-promises
    dispatch(fetchLeaderboard());
  };

  const rangeCaption = period
    ? period.type === 'year'
      ? `FY ${period.year}-${String(period.year + 1).slice(-2)}  ·  ${dayjs(period.start_date).format('D MMM YYYY')} – ${dayjs(period.end_date).format('D MMM YYYY')}`
      : dayjs(period.start_date).format('MMMM YYYY')
    : null;

  return (
    <div className="px-4">
      <PageHeader
        title={
          <span>
            <TrophyOutlined style={{ color: PRIMARY_COLOR, marginRight: 10 }} />
            Hall of Fame
          </span>
        }
        isBack={false}
        extra={
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
            <Segmented
              className="leaderboard-tabs"
              value={periodType}
              onChange={(value) => handlePeriodChange(value as 'month' | 'year')}
              options={[
                { label: 'This Month', value: 'month' },
                { label: 'This FY', value: 'year' },
              ]}
            />
            {availableRoles.length > 1 && (
              <Select
                className="leaderboard-role-select"
                value={selectedRoleId ?? undefined}
                onChange={(value: number) => handleRoleChange(value)}
                style={{ width: 180 }}
                options={availableRoles.map((r) => ({ value: r.id, label: r.label }))}
              />
            )}
            <Segmented
              className="leaderboard-tabs"
              value={scope}
              onChange={(value) => handleScopeChange(value as 'city' | 'pan_india')}
              options={[
                { label: cityLabel || 'My City', value: 'city' },
                { label: 'Pan India', value: 'pan_india' },
              ]}
            />
          </div>
        }
      />
      {rangeCaption && (
        <Text style={{ display: 'block', marginBottom: 16, color: '#5c6470', fontWeight: 500, fontSize: 13 }}>
          {rangeCaption}
        </Text>
      )}
      <Spin spinning={status === 'loading'}>
        {(!section || !section.rankings.length) && status !== 'loading' ? (
          <Empty description="No bookings recorded for this period yet." style={{ marginTop: 60 }} />
        ) : (
          section && <LeaderboardSectionCard section={section} myRank={myRank} />
        )}
      </Spin>
    </div>
  );
};

export default LeaderboardPage;
