'use client';

import { useState } from 'react';
import { Activity, ArrowDownCircle, ArrowUpCircle, AlertTriangle, FileCheck, Building2, Filter } from 'lucide-react';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { DashboardSwitcher } from '@/components/business/DashboardSwitcher';
import { Card, CardContent } from '@/components/ui/card';

// ============================================
// Mock 데이터
// ============================================

type EventType = 'deposit' | 'withdrawal' | 'issue' | 'approval' | 'vendor' | 'order' | 'system';

interface FeedEvent {
  id: number;
  type: EventType;
  title: string;
  description?: string;
  amount?: string;
  time: string;
  date: string; // 'today' | 'yesterday' | 'week'
  priority?: 'high' | 'medium' | 'low';
  status?: string;
}

const feedEvents: FeedEvent[] = [
  // 오늘
  { id: 1, type: 'vendor', title: '서울금속 신규 거래처 등록', time: '10:35', date: 'today' },
  { id: 2, type: 'vendor', title: '주식회사 부산화학 등록', time: '10:34', date: 'today' },
  { id: 3, type: 'deposit', title: '현대중공업 입금 확인', amount: '683만원', time: '10:33', date: 'today' },
  { id: 4, type: 'approval', title: '출장비 정산 승인 요청', description: '홍킬동 - 부산 출장', time: '10:31', date: 'today', priority: 'high', status: '대기' },
  { id: 5, type: 'deposit', title: 'E2E_TEST 판매처 입금', amount: '827만원', time: '10:33', date: 'today' },
  { id: 6, type: 'deposit', title: '제주관광 입금 확인', amount: '177만원', time: '10:17', date: 'today' },
  { id: 7, type: 'vendor', title: '제주관광 신규 거래처 등록', time: '10:16', date: 'today' },
  { id: 8, type: 'system', title: '어제 매출 실적 집계 완료', description: '목표 대비 95% 달성', time: '09:00', date: 'today' },
  // 어제
  { id: 9, type: 'issue', title: 'LG전자 미수금 120일 경과', description: '3,200만원 - 위험 등급 전환', time: '17:30', date: 'yesterday', priority: 'high' },
  { id: 10, type: 'deposit', title: '(주)대한건설 입금', amount: '2,000만원', time: '15:20', date: 'yesterday' },
  { id: 11, type: 'approval', title: '법인카드 사용 내역 승인', description: '김부장 - 접대비 52만원', time: '14:00', date: 'yesterday', status: '승인완료' },
  { id: 12, type: 'order', title: '현대건설 수주 확정', amount: '6,750만원', time: '11:30', date: 'yesterday' },
  { id: 13, type: 'issue', title: '전동개폐기 납기 지연 통보', description: '3일 지연 예상 - 대한건설', time: '10:00', date: 'yesterday', priority: 'medium' },
  { id: 14, type: 'withdrawal', title: '2월 급여 이체 완료', amount: '3,200만원', time: '09:30', date: 'yesterday' },
  // 이번주
  { id: 15, type: 'order', title: 'SK에코플랜트 수주', amount: '8,900만원', time: '2/7', date: 'week' },
  { id: 16, type: 'issue', title: '자재 단가 인상 통보', description: '동 파이프 +15%', time: '2/7', date: 'week', priority: 'medium' },
  { id: 17, type: 'deposit', title: '삼성엔지니어링 입금', amount: '5,000만원', time: '2/6', date: 'week' },
  { id: 18, type: 'approval', title: '구매 발주 승인', description: '전자부품 일괄 발주 1,800만원', time: '2/6', date: 'week', status: '승인완료' },
  { id: 19, type: 'vendor', title: '(주)미래산업 거래처 등록', time: '2/5', date: 'week' },
  { id: 20, type: 'issue', title: '품질 검사 부적합 2건', description: '제어반 PCB 불량', time: '2/5', date: 'week', priority: 'high' },
];

const filterConfig: { key: EventType | 'all'; label: string; icon: typeof Activity }[] = [
  { key: 'all', label: '전체', icon: Activity },
  { key: 'deposit', label: '입금', icon: ArrowDownCircle },
  { key: 'issue', label: '이슈', icon: AlertTriangle },
  { key: 'approval', label: '결재', icon: FileCheck },
  { key: 'vendor', label: '거래처', icon: Building2 },
];

// ============================================
// 이벤트 아이콘/색상
// ============================================

function getEventStyle(type: EventType) {
  switch (type) {
    case 'deposit': return { icon: ArrowDownCircle, color: 'text-green-500', bg: 'bg-green-50', ring: 'ring-green-200' };
    case 'withdrawal': return { icon: ArrowUpCircle, color: 'text-red-500', bg: 'bg-red-50', ring: 'ring-red-200' };
    case 'issue': return { icon: AlertTriangle, color: 'text-yellow-600', bg: 'bg-yellow-50', ring: 'ring-yellow-200' };
    case 'approval': return { icon: FileCheck, color: 'text-blue-500', bg: 'bg-blue-50', ring: 'ring-blue-200' };
    case 'vendor': return { icon: Building2, color: 'text-purple-500', bg: 'bg-purple-50', ring: 'ring-purple-200' };
    case 'order': return { icon: ArrowDownCircle, color: 'text-blue-600', bg: 'bg-blue-50', ring: 'ring-blue-200' };
    case 'system': return { icon: Activity, color: 'text-gray-500', bg: 'bg-gray-50', ring: 'ring-gray-200' };
  }
}

function PriorityDot({ priority }: { priority?: string }) {
  if (!priority) return null;
  const colors: Record<string, string> = { high: 'bg-red-500', medium: 'bg-yellow-500', low: 'bg-green-500' };
  return <span className={`w-2 h-2 rounded-full ${colors[priority] ?? 'bg-gray-400'}`} />;
}

function StatusTag({ status }: { status?: string }) {
  if (!status) return null;
  const styles: Record<string, string> = { '대기': 'bg-yellow-100 text-yellow-700', '승인완료': 'bg-green-100 text-green-700' };
  return <span className={`px-2 py-0.5 rounded-full text-[10px] font-medium ${styles[status] ?? 'bg-gray-100 text-gray-600'}`}>{status}</span>;
}

// ============================================
// 피드 아이템
// ============================================

function FeedItem({ event }: { event: FeedEvent }) {
  const style = getEventStyle(event.type);
  const Icon = style.icon;

  return (
    <div className="flex gap-3 p-3 rounded-xl hover:bg-muted/30 transition-colors cursor-pointer group">
      <div className={`flex-shrink-0 w-9 h-9 rounded-full ${style.bg} ring-1 ${style.ring} flex items-center justify-center`}>
        <Icon className={`w-4 h-4 ${style.color}`} />
      </div>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2">
          <PriorityDot priority={event.priority} />
          <p className="text-sm font-medium truncate">{event.title}</p>
        </div>
        {event.description && (
          <p className="text-xs text-muted-foreground mt-0.5">{event.description}</p>
        )}
        <div className="flex items-center gap-2 mt-1">
          {event.amount && <span className="text-xs font-semibold text-green-600">{event.amount}</span>}
          <StatusTag status={event.status} />
        </div>
      </div>
      <div className="flex-shrink-0 text-right">
        <span className="text-xs text-muted-foreground">{event.time}</span>
      </div>
    </div>
  );
}

// ============================================
// 요약 통계
// ============================================

function TodaySummary() {
  const stats = [
    { label: '오늘 입금', value: '1,687만원', color: 'text-green-600', bg: 'bg-green-50' },
    { label: '오늘 출금', value: '0원', color: 'text-red-600', bg: 'bg-red-50' },
    { label: '미처리 결재', value: '1건', color: 'text-blue-600', bg: 'bg-blue-50' },
    { label: '신규 이슈', value: '0건', color: 'text-yellow-600', bg: 'bg-yellow-50' },
  ];

  return (
    <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
      {stats.map((s) => (
        <div key={s.label} className={`${s.bg} rounded-xl p-4`}>
          <p className="text-xs text-muted-foreground">{s.label}</p>
          <p className={`text-lg font-bold mt-1 ${s.color}`}>{s.value}</p>
        </div>
      ))}
    </div>
  );
}

// ============================================
// 시간 그룹 헤더
// ============================================

function TimeGroupHeader({ label, count }: { label: string; count: number }) {
  return (
    <div className="flex items-center gap-3 py-3">
      <div className="h-px flex-1 bg-border" />
      <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
        {label} <span className="text-muted-foreground/60">({count})</span>
      </span>
      <div className="h-px flex-1 bg-border" />
    </div>
  );
}

// ============================================
// 메인 컴포넌트
// ============================================

export function DashboardType5() {
  const [filter, setFilter] = useState<EventType | 'all'>('all');

  const filtered = filter === 'all'
    ? feedEvents
    : feedEvents.filter((e) => e.type === filter);

  const todayEvents = filtered.filter((e) => e.date === 'today');
  const yesterdayEvents = filtered.filter((e) => e.date === 'yesterday');
  const weekEvents = filtered.filter((e) => e.date === 'week');

  return (
    <PageLayout>
      <div className="p-3 md:p-6">
        <PageHeader
          title="활동 피드"
          description="회사에서 일어나는 일을 시간순으로 확인합니다."
          icon={Activity}
          actions={<DashboardSwitcher />}
        />

        <div className="mt-6 space-y-6">
          <TodaySummary />

          {/* 필터 */}
          <div className="flex items-center gap-2 overflow-x-auto pb-1">
            <Filter className="w-4 h-4 text-muted-foreground flex-shrink-0" />
            {filterConfig.map((f) => {
              const Icon = f.icon;
              const isActive = filter === f.key;
              return (
                <button
                  key={f.key}
                  onClick={() => setFilter(f.key)}
                  className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium whitespace-nowrap transition-colors ${
                    isActive
                      ? 'bg-primary text-primary-foreground'
                      : 'bg-muted text-muted-foreground hover:bg-muted/80'
                  }`}
                >
                  <Icon className="w-3.5 h-3.5" />
                  {f.label}
                </button>
              );
            })}
          </div>

          {/* 타임라인 */}
          <Card>
            <CardContent className="p-2 md:p-4">
              {todayEvents.length > 0 && (
                <>
                  <TimeGroupHeader label="오늘" count={todayEvents.length} />
                  <div className="space-y-0.5">
                    {todayEvents.map((e) => <FeedItem key={e.id} event={e} />)}
                  </div>
                </>
              )}

              {yesterdayEvents.length > 0 && (
                <>
                  <TimeGroupHeader label="어제" count={yesterdayEvents.length} />
                  <div className="space-y-0.5">
                    {yesterdayEvents.map((e) => <FeedItem key={e.id} event={e} />)}
                  </div>
                </>
              )}

              {weekEvents.length > 0 && (
                <>
                  <TimeGroupHeader label="이번 주" count={weekEvents.length} />
                  <div className="space-y-0.5">
                    {weekEvents.map((e) => <FeedItem key={e.id} event={e} />)}
                  </div>
                </>
              )}

              {filtered.length === 0 && (
                <div className="py-16 text-center text-sm text-muted-foreground">
                  해당 필터에 맞는 이벤트가 없습니다.
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </PageLayout>
  );
}
