'use client';

import { useState } from 'react';
import {
  Check,
  AlertTriangle,
  Info,
  AlertCircle,
  TrendingUp,
  TrendingDown,
  ChevronDown,
  type LucideIcon,
} from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { formatKoreanAmount } from '@/lib/utils/amount';
import type { CheckPoint, CheckPointType, AmountCard, HighlightColor } from './types';

// 섹션별 컬러 테마 타입
export type SectionColorTheme = 'blue' | 'purple' | 'orange' | 'green' | 'red' | 'amber' | 'cyan' | 'pink' | 'emerald' | 'indigo';

// 컬러 테마별 스타일 (다크모드 지원 Tailwind 클래스)
export const SECTION_THEME_STYLES: Record<SectionColorTheme, { bgClass: string; borderClass: string; iconBg: string; labelClass: string; accentColor: string }> = {
  blue: { bgClass: 'bg-blue-50 dark:bg-blue-900/30', borderClass: 'border-blue-200 dark:border-blue-800', iconBg: '#3b82f6', labelClass: 'text-blue-700 dark:text-blue-300', accentColor: '#3b82f6' },
  purple: { bgClass: 'bg-purple-50 dark:bg-purple-900/30', borderClass: 'border-purple-200 dark:border-purple-800', iconBg: '#a855f7', labelClass: 'text-purple-700 dark:text-purple-300', accentColor: '#a855f7' },
  orange: { bgClass: 'bg-orange-50 dark:bg-orange-900/30', borderClass: 'border-orange-200 dark:border-orange-800', iconBg: '#f97316', labelClass: 'text-orange-700 dark:text-orange-300', accentColor: '#f97316' },
  green: { bgClass: 'bg-green-50 dark:bg-green-900/30', borderClass: 'border-green-200 dark:border-green-800', iconBg: '#22c55e', labelClass: 'text-green-700 dark:text-green-300', accentColor: '#22c55e' },
  red: { bgClass: 'bg-red-50 dark:bg-red-900/30', borderClass: 'border-red-200 dark:border-red-800', iconBg: '#ef4444', labelClass: 'text-red-700 dark:text-red-300', accentColor: '#ef4444' },
  amber: { bgClass: 'bg-amber-50 dark:bg-amber-900/30', borderClass: 'border-amber-200 dark:border-amber-800', iconBg: '#f59e0b', labelClass: 'text-amber-700 dark:text-amber-300', accentColor: '#f59e0b' },
  cyan: { bgClass: 'bg-cyan-50 dark:bg-cyan-900/30', borderClass: 'border-cyan-200 dark:border-cyan-800', iconBg: '#06b6d4', labelClass: 'text-cyan-700 dark:text-cyan-300', accentColor: '#06b6d4' },
  pink: { bgClass: 'bg-pink-50 dark:bg-pink-900/30', borderClass: 'border-pink-200 dark:border-pink-800', iconBg: '#ec4899', labelClass: 'text-pink-700 dark:text-pink-300', accentColor: '#ec4899' },
  emerald: { bgClass: 'bg-emerald-50 dark:bg-emerald-900/30', borderClass: 'border-emerald-200 dark:border-emerald-800', iconBg: '#10b981', labelClass: 'text-emerald-700 dark:text-emerald-300', accentColor: '#10b981' },
  indigo: { bgClass: 'bg-indigo-50 dark:bg-indigo-900/30', borderClass: 'border-indigo-200 dark:border-indigo-800', iconBg: '#6366f1', labelClass: 'text-indigo-700 dark:text-indigo-300', accentColor: '#6366f1' },
};

/**
 * USD 달러 포맷 함수
 */
const formatUSD = (amount: number): string => {
  return '$ ' + new Intl.NumberFormat('en-US').format(amount);
};

/**
 * 하이라이트 색상 클래스 반환
 */
export const getHighlightColorClass = (color: HighlightColor): string => {
  switch (color) {
    case 'red':
      return 'text-red-600';
    case 'green':
      return 'text-green-600';
    case 'blue':
      return 'text-blue-600';
    default:
      return 'text-red-600';
  }
};

/**
 * 체크포인트 아이콘
 */
export const CheckPointIcon = ({ type }: { type: CheckPointType }) => {
  switch (type) {
    case 'success':
      return <Check className="h-4 w-4 text-green-600 flex-shrink-0" />;
    case 'warning':
      return <AlertTriangle className="h-4 w-4 text-amber-600 flex-shrink-0" />;
    case 'error':
      return <AlertCircle className="h-4 w-4 text-red-600 flex-shrink-0" />;
    case 'info':
    default:
      return <Info className="h-4 w-4 text-blue-600 flex-shrink-0" />;
  }
};

/**
 * 메시지 내 하이라이트 텍스트를 찾아서 색상 적용하는 함수
 */
const renderMessageWithHighlights = (
  message: string,
  highlights?: { text: string; color: HighlightColor }[]
): React.ReactNode => {
  if (!highlights || highlights.length === 0) {
    return message;
  }

  // 하이라이트를 적용할 패턴들을 정규식으로 만듦
  const parts: React.ReactNode[] = [];
  let remainingText = message;
  let keyIndex = 0;

  // 메시지에서 하이라이트 텍스트를 찾아 분리
  highlights.forEach((highlight) => {
    const index = remainingText.indexOf(highlight.text);
    if (index !== -1) {
      // 하이라이트 앞 텍스트
      if (index > 0) {
        parts.push(remainingText.substring(0, index));
      }
      // 하이라이트 텍스트 (색상 적용)
      parts.push(
        <span key={keyIndex++} className={cn('font-medium', getHighlightColorClass(highlight.color))}>
          {highlight.text}
        </span>
      );
      remainingText = remainingText.substring(index + highlight.text.length);
    }
  });

  // 남은 텍스트 추가
  if (remainingText) {
    parts.push(remainingText);
  }

  return parts.length > 0 ? parts : message;
};

/**
 * 체크포인트 아이템 컴포넌트
 */
export const CheckPointItem = ({ checkpoint }: { checkpoint: CheckPoint }) => {
  return (
    <div className="flex items-start gap-2 py-1">
      <div className="mt-0.5">
        <CheckPointIcon type={checkpoint.type} />
      </div>
      <p className="text-sm text-muted-foreground">
        {checkpoint.highlights && checkpoint.highlights.length > 0 ? (
          renderMessageWithHighlights(checkpoint.message, checkpoint.highlights)
        ) : (
          <>
            {checkpoint.message}
            {checkpoint.highlight && (
              <span className="text-red-600 font-medium"> {checkpoint.highlight}</span>
            )}
          </>
        )}
      </p>
    </div>
  );
};

/**
 * 섹션 타이틀 컴포넌트 (아이콘 지원 버전)
 */
export const SectionTitle = ({
  title,
  badge,
  actionButton,
  icon: Icon,
  colorTheme,
}: {
  title: string;
  badge?: 'warning' | 'success' | 'info' | 'error';
  actionButton?: { label: string; onClick: () => void };
  icon?: LucideIcon;
  colorTheme?: SectionColorTheme;
}) => {
  const themeStyle = colorTheme ? SECTION_THEME_STYLES[colorTheme] : null;

  return (
    <div className="flex items-center justify-between mb-4">
      <div className="flex items-center gap-3">
        {Icon && themeStyle ? (
          <div
            className="p-1.5 rounded-lg"
            style={{ backgroundColor: themeStyle.iconBg }}
          >
            <Icon className="h-4 w-4 text-white" />
          </div>
        ) : (
          <div className={cn(
            "w-1.5 h-6 rounded-full",
            badge === 'warning' ? 'bg-amber-500' :
            badge === 'success' ? 'bg-green-500' :
            badge === 'info' ? 'bg-blue-500' : 'bg-red-500'
          )} />
        )}
        <h3 className="text-lg font-semibold text-foreground">{title}</h3>
      </div>
      {actionButton && (
        <Button
          variant="default"
          size="sm"
          className="bg-blue-600 hover:bg-blue-700 text-white"
          onClick={actionButton.onClick}
        >
          {actionButton.label}
        </Button>
      )}
    </div>
  );
};

/**
 * 금액 카드 컴포넌트 (아이콘/컬러 테마 지원)
 */
export const AmountCardItem = ({
  card,
  onClick,
  className,
  icon: Icon,
  colorTheme,
  showTrend,
  trendValue,
  trendDirection,
  showCountBadge,
  subLabelAsBadge,
}: {
  card: AmountCard;
  onClick?: () => void;
  className?: string;
  icon?: LucideIcon;
  colorTheme?: SectionColorTheme;
  showTrend?: boolean;
  trendValue?: string;
  trendDirection?: 'up' | 'down';
  showCountBadge?: boolean;
  subLabelAsBadge?: boolean;
}) => {
  const themeStyle = colorTheme ? SECTION_THEME_STYLES[colorTheme] : null;

  // 금액 포맷 함수 (통화에 따라 분기)
  const formatCardAmount = (amount: number): string => {
    if (card.unit === '건') {
      return `${amount}건`;
    }
    if (card.currency === 'USD') {
      return formatUSD(amount);
    }
    return formatKoreanAmount(amount);
  };

  return (
    <Card
      className={cn(
        'relative border',
        onClick && 'cursor-pointer hover:shadow-lg transition-all hover:scale-[1.02]',
        card.isHighlighted && 'border-red-300 bg-red-50 dark:border-red-700 dark:bg-red-900/30',
        themeStyle && !card.isHighlighted && cn(themeStyle.bgClass, themeStyle.borderClass),
        className
      )}
    >
      {/* 건수 뱃지 (오른쪽 상단) */}
      {showCountBadge && card.subLabel && (
        <div
          className="absolute top-3 right-3 px-2 py-0.5 rounded-full text-xs font-bold text-white"
          style={{ backgroundColor: themeStyle ? themeStyle.iconBg : '#ef4444' }}
        >
          {card.subLabel}
        </div>
      )}

      <CardContent
        className={cn(
          "p-4 flex flex-col",
          card.subItems && card.subItems.length > 0 ? "min-h-[140px]" : showTrend && trendValue ? "min-h-[130px]" : "min-h-[110px]"
        )}
        onClick={onClick}
      >
        {/* 아이콘 + 라벨 */}
        <div className="flex items-center gap-2 mb-3">
          {Icon && themeStyle && !card.isHighlighted && (
            <div
              className="p-1.5 rounded-lg shrink-0"
              style={{ backgroundColor: themeStyle.iconBg }}
            >
              <Icon className="h-4 w-4 text-white" />
            </div>
          )}
          <p
            className={cn(
              "text-sm font-medium truncate",
              card.isHighlighted ? 'text-red-600' : themeStyle ? themeStyle.labelClass : 'text-muted-foreground'
            )}
          >
            {card.label}
          </p>
        </div>

        {/* 금액 */}
        <p className={cn(
          "text-2xl font-bold text-foreground",
          card.isHighlighted && 'text-red-600'
        )}>
          {formatCardAmount(card.amount)}
        </p>

        {/* 트렌드 표시 (pill 형태, 금액 아래에 배치) */}
        {showTrend && trendValue && (
          <div
            className={cn(
              "flex items-center gap-1 px-2 py-1 rounded-full text-xs font-semibold mt-auto w-fit",
              trendDirection === 'up'
                ? 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300'
                : 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'
            )}
          >
            {trendDirection === 'up' ? (
              <TrendingUp className="h-3 w-3 shrink-0" />
            ) : (
              <TrendingDown className="h-3 w-3 shrink-0" />
            )}
            <span>{trendValue}</span>
          </div>
        )}

        {/* subItems 배열이 있는 경우 (매출, 입금 등 다중 서브 정보) */}
        {!showTrend && card.subItems && card.subItems.length > 0 && (
          <div className="mt-auto space-y-0.5 text-xs text-muted-foreground">
            {card.subItems.map((item, idx) => (
              <div key={idx} className="flex justify-between gap-2">
                <span className="min-w-0 truncate">{item.label}</span>
                <span className="shrink-0 text-right">{typeof item.value === 'number' ? formatKoreanAmount(item.value) : item.value}</span>
              </div>
            ))}
          </div>
        )}

        {/* 기존 단일 서브 정보 */}
        {!showTrend && !card.subItems && (card.subAmount !== undefined || card.previousAmount !== undefined || card.subLabel || card.previousLabel) && (
          <div className="flex gap-4 mt-auto text-xs text-muted-foreground">
            {card.subAmount !== undefined && card.subLabel && (
              <span>{card.subLabel}: {card.unit === '건' ? `${card.subAmount}건` : formatKoreanAmount(card.subAmount)}</span>
            )}
            {card.previousLabel && (
              <span className="flex items-center gap-1">
                <TrendingUp className="h-3 w-3 text-green-600" />
                {card.previousLabel}
              </span>
            )}
            {card.subLabel && card.subAmount === undefined && !card.previousLabel && (
              subLabelAsBadge && themeStyle ? (
                <span
                  className={cn(
                    "text-xs font-medium px-2 py-0.5 rounded-full border truncate w-fit max-w-full",
                    themeStyle.labelClass
                  )}
                  style={{
                    backgroundColor: `${themeStyle.iconBg}15`,
                    borderColor: `${themeStyle.iconBg}30`,
                  }}
                >
                  {card.subLabel}
                </span>
              ) : (
                <span>{card.subLabel}</span>
              )
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
};

/**
 * 이슈 카드 그리드 아이템 (StatCards 스타일)
 */
export const IssueCardItem = ({
  label,
  count,
  subLabel,
  isHighlighted,
  onClick,
}: {
  label: string;
  count: number | string;
  subLabel?: string;
  isHighlighted?: boolean;
  onClick?: () => void;
}) => {
  return (
    <Card
      className={cn(
        'cursor-pointer hover:shadow-md transition-shadow',
        isHighlighted && 'bg-red-500 border-red-500 hover:bg-red-600'
      )}
      onClick={onClick}
    >
      <CardContent className="p-4 md:p-6">
        <p className={cn(
          "text-sm font-medium",
          isHighlighted ? 'text-white' : 'text-muted-foreground'
        )}>
          {label}
        </p>
        <p className={cn(
          "mt-2",
          typeof count === 'number'
            ? "text-lg xs:text-xl md:text-2xl lg:text-3xl font-bold"
            : "text-base xs:text-lg md:text-xl lg:text-2xl font-medium",
          isHighlighted ? 'text-white' : 'text-foreground'
        )}>
          {typeof count === 'number' ? `${count}건` : count}
        </p>
        {subLabel && (
          <p className={cn(
            "text-sm font-medium mt-1",
            isHighlighted ? 'text-white/90' : 'text-muted-foreground'
          )}>
            {subLabel}
          </p>
        )}
      </CardContent>
    </Card>
  );
};

/**
 * 접기/펼치기 가능한 대시보드 카드
 * - 다크 헤더 + 흰색 바디 패턴의 공통 컴포넌트
 * - 헤더 클릭 시 바디 토글
 */
interface CollapsibleDashboardCardProps {
  icon: React.ReactNode;
  title: string;
  subtitle?: string;
  rightElement?: React.ReactNode;
  children: React.ReactNode;
  defaultOpen?: boolean;
  bodyClassName?: string;
}

export function CollapsibleDashboardCard({
  icon,
  title,
  subtitle,
  rightElement,
  children,
  defaultOpen = true,
  bodyClassName,
}: CollapsibleDashboardCardProps) {
  const [isOpen, setIsOpen] = useState(defaultOpen);

  return (
    <div className="rounded-xl border border-border lg:overflow-hidden">
      <div
        className={cn(
          'bg-slate-800 dark:bg-slate-700 px-6 py-4 sticky top-12 z-10 lg:static cursor-pointer select-none',
          isOpen ? 'rounded-t-xl' : 'rounded-xl'
        )}
        onClick={() => setIsOpen(!isOpen)}
      >
        <div className="flex flex-col items-center gap-2 lg:flex-row lg:items-center lg:justify-between">
          <div className="flex flex-col items-center gap-2 lg:flex-row lg:gap-3">
            <div className="bg-white/10 p-2 rounded-lg">
              {icon}
            </div>
            <div className="text-center lg:text-left">
              <h3 className="text-lg font-semibold text-white">{title}</h3>
              {subtitle && <p className="text-sm text-slate-300">{subtitle}</p>}
            </div>
          </div>
          <div className="flex items-center gap-2">
            {rightElement}
            <ChevronDown
              className={cn(
                'h-4 w-4 text-white/70 transition-transform duration-200',
                !isOpen && '-rotate-90'
              )}
            />
          </div>
        </div>
      </div>
      {isOpen && (
        <div className={cn('bg-card text-card-foreground', bodyClassName ?? 'p-6')}>
          {children}
        </div>
      )}
    </div>
  );
}

/**
 * 데이터가 없거나 API 미연동 섹션에 표시하는 빈 상태 컴포넌트
 */
export function EmptySection({ title, message = '데이터를 불러올 수 없습니다' }: { title: string; message?: string }) {
  return (
    <Card className="border-dashed">
      <CardContent className="flex flex-col items-center justify-center py-12 text-muted-foreground">
        <Info className="mb-3 h-8 w-8 opacity-40" />
        <p className="text-sm font-medium">{title}</p>
        <p className="mt-1 text-xs">{message}</p>
      </CardContent>
    </Card>
  );
}