'use client';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { StatCards } from '../StatCards';
import { Clock, AlertTriangle, FileText, Truck, Users } from 'lucide-react';
import type { ScheduleTabData } from '../hooks/useDashboardType2';
import type { TodayIssueListItem } from '@/components/business/CEODashboard/types';
import { scheduleTodayItems, scheduleIssueItems } from '../mockData';

function LoadingSkeleton() {
  return (
    <div className="space-y-6">
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {[...Array(4)].map((_, i) => (
          <div key={i} className="animate-pulse bg-muted rounded-xl h-[88px]" />
        ))}
      </div>
      <div className="animate-pulse bg-muted rounded-xl h-[200px]" />
      <div className="animate-pulse bg-muted rounded-xl h-[200px]" />
    </div>
  );
}

// 뱃지 타입 → 아이콘 타입 매핑
function getIconType(badge: string): string {
  if (badge.includes('수주') || badge.includes('결재')) return 'meeting';
  if (badge.includes('입금') || badge.includes('출금')) return 'task';
  if (badge.includes('신고') || badge.includes('세금')) return 'report';
  if (badge.includes('재고') || badge.includes('납품')) return 'delivery';
  return 'task';
}

// 뱃지 타입 → 우선순위 매핑
function getPriority(item: TodayIssueListItem): string {
  if (item.needsApproval) return 'high';
  if (item.notificationType === 'bad_debt' || item.notificationType === 'safety_stock') return 'high';
  return 'medium';
}

export function ScheduleTab({ data }: { data: ScheduleTabData }) {
  if (data.loading) return <LoadingSkeleton />;

  // API 데이터가 있으면 사용, 없으면 mock fallback
  const hasApiData = data.todayItems.length > 0 || data.issueItems.length > 0;

  return (
    <div className="space-y-6">
      <StatCards stats={data.stats} />

      <Card>
        <CardHeader>
          <CardTitle className="text-base font-semibold">오늘 일정</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-4 gap-3">
            {hasApiData ? (
              data.todayItems.length > 0 ? (
                data.todayItems.map((item) => (
                  <div key={item.id} className="flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/30 transition-colors">
                    <div className="flex-shrink-0 mt-0.5">
                      <ScheduleIcon type={getIconType(item.badge)} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium">{item.content}</p>
                      <div className="flex items-center gap-2 mt-0.5">
                        <span className="text-xs text-muted-foreground">{item.badge}</span>
                      </div>
                    </div>
                    <div className="flex-shrink-0">
                      <span className="text-xs text-muted-foreground bg-muted px-2 py-1 rounded">{item.time}</span>
                    </div>
                  </div>
                ))
              ) : (
                <p className="text-sm text-muted-foreground col-span-full py-4 text-center">오늘 일정이 없습니다.</p>
              )
            ) : (
              scheduleTodayItems.map((item) => (
                <div key={item.id} className="flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/30 transition-colors">
                  <div className="flex-shrink-0 mt-0.5">
                    <ScheduleIcon type={item.type} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium">{item.title}</p>
                    <p className="text-xs text-muted-foreground mt-0.5">{item.person}</p>
                  </div>
                  <div className="flex-shrink-0">
                    <span className="text-xs text-muted-foreground bg-muted px-2 py-1 rounded">{item.time}</span>
                  </div>
                </div>
              ))
            )}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-base font-semibold">미처리 이슈</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-4 gap-3">
            {hasApiData ? (
              data.issueItems.length > 0 ? (
                data.issueItems.map((item) => (
                  <div key={item.id} className="flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/30 transition-colors">
                    <div className="flex-shrink-0 mt-0.5">
                      <PriorityIcon priority={getPriority(item)} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium">{item.content}</p>
                      <div className="flex items-center gap-2 mt-0.5">
                        <span className="text-xs text-muted-foreground">{item.time}</span>
                        <span className="text-xs text-muted-foreground">|</span>
                        <span className="text-xs text-muted-foreground">{item.badge}</span>
                      </div>
                    </div>
                    <div className="flex-shrink-0">
                      <PriorityBadge priority={getPriority(item)} />
                    </div>
                  </div>
                ))
              ) : (
                <p className="text-sm text-muted-foreground col-span-full py-4 text-center">미처리 이슈가 없습니다.</p>
              )
            ) : (
              scheduleIssueItems.map((item) => (
                <div key={item.id} className="flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/30 transition-colors">
                  <div className="flex-shrink-0 mt-0.5">
                    <PriorityIcon priority={item.priority} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium">{item.title}</p>
                    <div className="flex items-center gap-2 mt-0.5">
                      <span className="text-xs text-muted-foreground">{item.date}</span>
                      <span className="text-xs text-muted-foreground">|</span>
                      <span className="text-xs text-muted-foreground">{item.assignee}</span>
                    </div>
                  </div>
                  <div className="flex-shrink-0">
                    <PriorityBadge priority={item.priority} />
                  </div>
                </div>
              ))
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function ScheduleIcon({ type }: { type: string }) {
  const iconClass = "w-4 h-4";
  switch (type) {
    case 'meeting': return <Users className={`${iconClass} text-blue-500`} />;
    case 'task': return <FileText className={`${iconClass} text-green-500`} />;
    case 'report': return <Clock className={`${iconClass} text-orange-500`} />;
    case 'delivery': return <Truck className={`${iconClass} text-purple-500`} />;
    default: return <Clock className={`${iconClass} text-gray-500`} />;
  }
}

function PriorityIcon({ priority }: { priority: string }) {
  if (priority === 'high') return <AlertTriangle className="w-4 h-4 text-red-500" />;
  return <AlertTriangle className="w-4 h-4 text-yellow-500" />;
}

function PriorityBadge({ priority }: { priority: string }) {
  const styles: Record<string, string> = {
    high: 'bg-red-100 text-red-700',
    medium: 'bg-yellow-100 text-yellow-700',
    low: 'bg-green-100 text-green-700',
  };
  const labels: Record<string, string> = { high: '긴급', medium: '보통', low: '낮음' };
  return (
    <span className={`inline-block px-2 py-0.5 rounded-full text-xs font-medium ${styles[priority] ?? 'bg-gray-100 text-gray-600'}`}>
      {labels[priority] ?? priority}
    </span>
  );
}
