'use client';

import { useState, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { toast } from 'sonner';
import {
  ShoppingCart,
  AlertCircle,
  Package,
  Receipt,
  FileText,
  CheckCircle2,
  Building2,
  TrendingUp,
  TrendingDown,
  Info,
  type LucideIcon,
} from 'lucide-react';
import type { TodayIssueListItem, TodayIssueNotificationType } from '../types';

// 뱃지 스타일 매핑 (notification_type 코드 기반)
interface BadgeStyle {
  bg: string;
  text: string;
  iconBg: string;
  Icon: LucideIcon;
}

// notification_type 코드 기반 스타일 매핑 (API 고정값 사용)
const NOTIFICATION_STYLES: Record<TodayIssueNotificationType, BadgeStyle> = {
  sales_order: { bg: 'bg-blue-50', text: 'text-blue-700', iconBg: 'bg-blue-500', Icon: ShoppingCart },
  bad_debt: { bg: 'bg-purple-50', text: 'text-purple-700', iconBg: 'bg-purple-500', Icon: AlertCircle },
  safety_stock: { bg: 'bg-orange-50', text: 'text-orange-700', iconBg: 'bg-orange-500', Icon: Package },
  expected_expense: { bg: 'bg-green-50', text: 'text-green-700', iconBg: 'bg-green-500', Icon: Receipt },
  vat_report: { bg: 'bg-red-50', text: 'text-red-700', iconBg: 'bg-red-500', Icon: FileText },
  approval_request: { bg: 'bg-amber-50', text: 'text-amber-700', iconBg: 'bg-amber-500', Icon: CheckCircle2 },
  new_vendor: { bg: 'bg-emerald-50', text: 'text-emerald-700', iconBg: 'bg-emerald-500', Icon: Building2 },
  deposit: { bg: 'bg-cyan-50', text: 'text-cyan-700', iconBg: 'bg-cyan-500', Icon: TrendingUp },
  withdrawal: { bg: 'bg-pink-50', text: 'text-pink-700', iconBg: 'bg-pink-500', Icon: TrendingDown },
  other: { bg: 'bg-gray-50', text: 'text-gray-700', iconBg: 'bg-gray-500', Icon: Info },
};

// 신용등급 색상 매핑 (A=녹색, B=노랑, C=주황, D=빨강)
type CreditRating = 'A' | 'B' | 'C' | 'D';
const CREDIT_RATING_COLORS: Record<CreditRating, string> = {
  A: 'bg-green-500 hover:bg-green-600 text-white',
  B: 'bg-yellow-500 hover:bg-yellow-600 text-white',
  C: 'bg-orange-500 hover:bg-orange-600 text-white',
  D: 'bg-red-500 hover:bg-red-600 text-white',
};

// 랜덤 신용등급 생성 (A~D)
const getRandomCreditRating = (): CreditRating => {
  const ratings: CreditRating[] = ['A', 'B', 'C', 'D'];
  return ratings[Math.floor(Math.random() * ratings.length)];
};

// 필터 옵션 키 (notification_type 코드 기반)
const FILTER_KEYS = [
  'all',
  'sales_order',
  'bad_debt',
  'safety_stock',
  'expected_expense',
  'vat_report',
  'approval_request',
  'new_vendor',
  'deposit',
  'withdrawal',
  'other',
] as const;

// notification_type → 한글 라벨 매핑 (필터 표시용)
// 백엔드 TodayIssue.php BADGE 상수와 동기화!
const NOTIFICATION_TYPE_LABELS: Record<TodayIssueNotificationType, string> = {
  sales_order: '수주등록',
  bad_debt: '추심이슈',
  safety_stock: '안전재고',
  expected_expense: '지출 승인대기',
  vat_report: '세금 신고',
  approval_request: '결재 요청',
  new_vendor: '신규거래처',
  deposit: '입금',
  withdrawal: '출금',
  other: '기타',
};

interface TodayIssueSectionProps {
  items: TodayIssueListItem[];
}

export function TodayIssueSection({ items }: TodayIssueSectionProps) {
  const router = useRouter();
  const [filter, setFilter] = useState<string>('all');
  const [dismissedIds, setDismissedIds] = useState<Set<string>>(new Set());

  // 확인되지 않은 아이템만 필터링
  const activeItems = items.filter((item) => !dismissedIds.has(item.id));

  // 신규업체 아이템별 랜덤 신용등급 생성 (세션 동안 유지)
  const creditRatings = useMemo(() => {
    const ratings: Record<string, CreditRating> = {};
    items.forEach((item) => {
      if (item.notificationType === 'new_vendor') {
        ratings[item.id] = getRandomCreditRating();
      }
    });
    return ratings;
  }, [items]);

  // 항목별 수량 계산 (notification_type 코드 기반)
  const itemCounts = useMemo(() => {
    const counts: Record<string, number> = { all: activeItems.length };
    FILTER_KEYS.forEach((key) => {
      if (key !== 'all') {
        counts[key] = activeItems.filter((item) => item.notificationType === key).length;
      }
    });
    return counts;
  }, [activeItems]);

  // 필터 옵션 (notification_type 코드 기반, 한글 라벨 표시)
  const filterOptions = useMemo(() => {
    return FILTER_KEYS.map((key) => ({
      value: key,
      label: key === 'all' ? '전체' : NOTIFICATION_TYPE_LABELS[key as TodayIssueNotificationType],
      count: itemCounts[key] || 0,
    }));
  }, [itemCounts]);

  // 필터링된 아이템 (notification_type 코드 기반)
  const filteredItems = filter === 'all'
    ? activeItems
    : activeItems.filter((item) => item.notificationType === filter);

  // 아이템 클릭
  const handleItemClick = (item: TodayIssueListItem) => {
    if (item.path) {
      router.push(item.path);
    }
  };

  // 확인 버튼 클릭 (목록에서 제거)
  const handleDismiss = (item: TodayIssueListItem) => {
    setDismissedIds((prev) => new Set(prev).add(item.id));
    toast.success(`"${item.content}" 확인 완료`);
  };

  // 승인 버튼 클릭
  const handleApprove = (item: TodayIssueListItem) => {
    setDismissedIds((prev) => new Set(prev).add(item.id));
    toast.success(`"${item.content}" 승인 처리되었습니다.`);
  };

  // 반려 버튼 클릭
  const handleReject = (item: TodayIssueListItem) => {
    setDismissedIds((prev) => new Set(prev).add(item.id));
    toast.error(`"${item.content}" 반려 처리되었습니다.`);
  };

  return (
    <Card>
      <CardContent className="p-6">
        {/* 헤더 */}
        <div className="flex items-center mb-4">
          <h2 className="text-lg font-semibold text-gray-900">오늘의 이슈</h2>
          <Select value={filter} onValueChange={setFilter}>
            <SelectTrigger className="w-44 h-9 ml-auto">
              <SelectValue placeholder="전체" />
            </SelectTrigger>
            <SelectContent>
              {filterOptions.map((option) => (
                <SelectItem key={option.value} value={option.value}>
                  <div className="flex items-center justify-between w-full gap-3">
                    <span>{option.label}</span>
                    <span className="bg-gray-100 text-gray-600 text-xs px-2 py-0.5 rounded-full font-medium">
                      {option.count}
                    </span>
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* 리스트 - 반응형 그리드 (4열 → 1열) */}
        <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-3 max-h-[400px] overflow-y-auto pr-1">
          {filteredItems.length === 0 ? (
            <div className="col-span-full text-center py-8 text-gray-500">
              표시할 이슈가 없습니다.
            </div>
          ) : (
            filteredItems.map((item) => {
              // notification_type 코드 기반 스타일 매핑 (안정적)
              const badgeStyle = NOTIFICATION_STYLES[item.notificationType] || NOTIFICATION_STYLES.other;
              const BadgeIcon = badgeStyle.Icon;
              // 표시용 한글 라벨
              const displayLabel = NOTIFICATION_TYPE_LABELS[item.notificationType] || item.badge;

              return (
              <div
                key={item.id}
                className={`flex items-center gap-2 p-3 border rounded-lg hover:shadow-md transition-all cursor-pointer ${badgeStyle.bg} border-transparent hover:border-gray-200`}
                onClick={() => handleItemClick(item)}
              >
                {/* 아이콘 + 뱃지 */}
                <div className="flex items-center gap-1.5 shrink-0">
                  <div className={`p-1 rounded ${badgeStyle.iconBg}`}>
                    <BadgeIcon className="h-3 w-3 text-white" />
                  </div>
                  <span className={`text-xs font-semibold ${badgeStyle.text}`}>
                    {displayLabel}
                  </span>
                </div>

                {/* 내용 */}
                <span className="text-sm text-gray-800 truncate flex-1 min-w-0">
                  {item.content}
                </span>

                {/* 신용등급 배지 (신규업체인 경우) */}
                {item.notificationType === 'new_vendor' && creditRatings[item.id] && (
                  <Button
                    size="sm"
                    className={`h-6 px-2 text-xs shrink-0 ${CREDIT_RATING_COLORS[creditRatings[item.id]]}`}
                    onClick={(e) => {
                      e.stopPropagation();
                      // API에서 이미 ?modal=credit 포함된 path 사용
                      if (item.path) {
                        router.push(item.path);
                      }
                    }}
                  >
                    신용 {creditRatings[item.id]}
                  </Button>
                )}

                {/* 시간 */}
                <span className="text-xs text-gray-500 whitespace-nowrap shrink-0">
                  {item.time}
                </span>

                {/* TODO: 버튼 - API 구현 후 활성화
                <div className="flex items-center gap-1 shrink-0" onClick={(e) => e.stopPropagation()}>
                  {item.needsApproval && (
                    <>
                      <Button
                        size="sm"
                        variant="default"
                        className="h-6 px-2 bg-blue-500 hover:bg-blue-600 text-white text-xs"
                        onClick={() => handleApprove(item)}
                      >
                        승인
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        className="h-6 px-2 text-xs"
                        onClick={() => handleReject(item)}
                      >
                        반려
                      </Button>
                    </>
                  )}
                  {!item.needsApproval && (
                    <Button
                      size="sm"
                      variant="outline"
                      className="h-6 px-2 text-xs text-gray-600 hover:text-green-600 hover:border-green-600 hover:bg-green-50"
                      onClick={() => handleDismiss(item)}
                    >
                      확인
                    </Button>
                  )}
                </div>
                */}
              </div>
            );
            })
          )}
        </div>
      </CardContent>
    </Card>
  );
}