'use client';

import { useState, useMemo, useCallback, useRef, useLayoutEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { DatePicker } from '@/components/ui/date-picker';
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,
  ChevronLeft,
  ChevronRight,
  Loader2,
  type LucideIcon,
} from 'lucide-react';
import { CollapsibleDashboardCard } from '../components';
import { usePastIssue } from '@/hooks/useCEODashboard';
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 dark:bg-blue-900/30', text: 'text-blue-700 dark:text-blue-300', iconBg: 'bg-blue-500', Icon: ShoppingCart },
  bad_debt: { bg: 'bg-purple-50 dark:bg-purple-900/30', text: 'text-purple-700 dark:text-purple-300', iconBg: 'bg-purple-500', Icon: AlertCircle },
  safety_stock: { bg: 'bg-orange-50 dark:bg-orange-900/30', text: 'text-orange-700 dark:text-orange-300', iconBg: 'bg-orange-500', Icon: Package },
  expected_expense: { bg: 'bg-green-50 dark:bg-green-900/30', text: 'text-green-700 dark:text-green-300', iconBg: 'bg-green-500', Icon: Receipt },
  vat_report: { bg: 'bg-red-50 dark:bg-red-900/30', text: 'text-red-700 dark:text-red-300', iconBg: 'bg-red-500', Icon: FileText },
  approval_request: { bg: 'bg-amber-50 dark:bg-amber-900/30', text: 'text-amber-700 dark:text-amber-300', iconBg: 'bg-amber-500', Icon: CheckCircle2 },
  new_vendor: { bg: 'bg-emerald-50 dark:bg-emerald-900/30', text: 'text-emerald-700 dark:text-emerald-300', iconBg: 'bg-emerald-500', Icon: Building2 },
  deposit: { bg: 'bg-cyan-50 dark:bg-cyan-900/30', text: 'text-cyan-700 dark:text-cyan-300', iconBg: 'bg-cyan-500', Icon: TrendingUp },
  withdrawal: { bg: 'bg-pink-50 dark:bg-pink-900/30', text: 'text-pink-700 dark:text-pink-300', iconBg: 'bg-pink-500', Icon: TrendingDown },
  other: { bg: 'bg-muted/50', text: 'text-muted-foreground', 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[];
}

// 날짜를 YYYY-MM-DD 형식으로 포맷
function formatDateParam(date: Date): string {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return `${y}-${m}-${d}`;
}

// 날짜를 "1월 29일 수요일" 형식으로 표시
const DAY_NAMES = ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'];
function formatDateDisplay(date: Date): string {
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const dayName = DAY_NAMES[date.getDay()];
  return `${month}월 ${day}일 ${dayName}`;
}

// 어제 날짜 생성
function getYesterday(): Date {
  const d = new Date();
  d.setHours(0, 0, 0, 0);
  d.setDate(d.getDate() - 1);
  return d;
}

// 두 날짜가 같은 날인지 비교
function isSameDay(a: Date, b: Date): boolean {
  return a.getFullYear() === b.getFullYear()
    && a.getMonth() === b.getMonth()
    && a.getDate() === b.getDate();
}

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

  // 탭 & 날짜 상태
  const [activeTab, setActiveTab] = useState<'today' | 'past'>('today');
  const [pastDate, setPastDate] = useState<Date>(getYesterday);

  // 그리드 높이 유지 (로딩 시 들썩임 방지)
  const gridRef = useRef<HTMLDivElement>(null);
  const lastHeightRef = useRef<number>(0);

  // 이전 이슈 API 호출 (past 탭일 때만)
  const pastDateParam = activeTab === 'past' ? formatDateParam(pastDate) : null;
  const { data: pastIssueData, loading: pastLoading } = usePastIssue(pastDateParam);

  // 현재 탭에 따른 데이터 소스
  const currentItems = activeTab === 'today' ? items : (pastIssueData?.items ?? []);

  // 콘텐츠가 있을 때 높이 저장, 로딩 중이면 이전 높이 유지
  useLayoutEffect(() => {
    if (!gridRef.current) return;
    if (pastLoading && lastHeightRef.current > 0) {
      gridRef.current.style.minHeight = `${lastHeightRef.current}px`;
    } else {
      lastHeightRef.current = gridRef.current.scrollHeight;
      gridRef.current.style.minHeight = '';
    }
  }, [pastLoading, currentItems.length]);

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

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

  // 항목별 수량 계산 (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]);

  // 탭 변경 핸들러
  const handleTabChange = useCallback((value: string) => {
    setActiveTab(value as 'today' | 'past');
    setFilter('all');
    setDismissedIds(new Set());
  }, []);

  // 날짜 네비게이션
  const yesterday = useMemo(() => getYesterday(), []);
  const isNextDisabled = isSameDay(pastDate, yesterday);

  // DatePicker 날짜 선택
  const handleDatePickerChange = useCallback((value: string) => {
    if (!value) return;
    const selected = new Date(value + 'T00:00:00');
    if (isNaN(selected.getTime())) return;
    if (selected >= new Date(new Date().setHours(0, 0, 0, 0))) return;
    setPastDate(selected);
    setFilter('all');
    setDismissedIds(new Set());
  }, []);

  const handlePrevDate = useCallback(() => {
    setPastDate((prev) => {
      const next = new Date(prev);
      next.setDate(next.getDate() - 1);
      return next;
    });
    setFilter('all');
    setDismissedIds(new Set());
  }, []);

  const handleNextDate = useCallback(() => {
    setPastDate((prev) => {
      const next = new Date(prev);
      next.setDate(next.getDate() + 1);
      // 어제까지만 허용
      if (next > yesterday) return prev;
      return next;
    });
    setFilter('all');
    setDismissedIds(new Set());
  }, [yesterday]);

  // 필터 옵션 (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 (
    <CollapsibleDashboardCard
      icon={<AlertCircle style={{ color: '#ffffff' }} className="h-5 w-5" />}
      title="오늘의 이슈"
      subtitle="주요 알림 및 이슈 현황"
    >
        {/* 필터/탭 영역 */}
        <div className="flex items-center gap-3 mb-4 flex-wrap">

          {/* 탭 */}
          <Tabs value={activeTab} onValueChange={handleTabChange} className="shrink-0">
            <TabsList className="h-8">
              <TabsTrigger value="today" className="text-xs px-3 h-7">오늘</TabsTrigger>
              <TabsTrigger value="past" className="text-xs px-3 h-7">이전 이슈</TabsTrigger>
            </TabsList>
          </Tabs>

          {/* 날짜 네비게이션 (이전 이슈 탭일 때만) */}
          {activeTab === 'past' && (
            <div className="flex items-center gap-1 min-w-0">
              <Button
                variant="outline"
                size="sm"
                className="h-8 px-1.5 shrink-0"
                onClick={handlePrevDate}
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <DatePicker
                value={formatDateParam(pastDate)}
                maxDate={yesterday}
                onChange={handleDatePickerChange}
                size="sm"
                displayFormat="yyyy년 MM월 dd일"
                className="min-w-0 flex-1"
                align="start"
                sideOffset={4}
              />
              <Button
                variant="outline"
                size="sm"
                className="h-8 px-1.5 shrink-0"
                onClick={handleNextDate}
                disabled={isNextDisabled}
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          )}

          {/* 필터 */}
          <Select value={filter} onValueChange={setFilter}>
            <SelectTrigger className="w-44 h-9">
              <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-muted text-muted-foreground text-xs px-2 py-0.5 rounded-full font-medium">
                      {option.count}
                    </span>
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* 리스트 - 반응형 그리드 (4열 → 1열) */}
        <div ref={gridRef} className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-3 max-h-[400px] overflow-y-auto pr-1">
          {activeTab === 'past' && pastLoading ? (
            <div className="col-span-full flex items-center justify-center py-8">
              <Loader2 className="h-5 w-5 animate-spin text-muted-foreground mr-2" />
              <span className="text-sm text-muted-foreground">데이터를 불러오는 중...</span>
            </div>
          ) : filteredItems.length === 0 ? (
            <div className="col-span-full text-center py-8 text-muted-foreground">
              {activeTab === 'past'
                ? `${formatDateDisplay(pastDate)}에 이슈가 없습니다.`
                : '표시할 이슈가 없습니다.'}
            </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-border`}
                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-foreground 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-muted-foreground 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-muted-foreground hover:text-green-600 hover:border-green-600 hover:bg-green-50"
                      onClick={() => handleDismiss(item)}
                    >
                      확인
                    </Button>
                  )}
                </div>
                */}
              </div>
            );
            })
          )}
        </div>
    </CollapsibleDashboardCard>
  );
}
