import { useQuery } from '@tanstack/react-query';
import { apiClient } from '../../lib/apiClient';
import type { Task } from '../../types';

const SECTIONS = [
  { key: '인사관리', titleEn: 'HR Management',     gradient: 'linear-gradient(120deg, #2a4a8a 0%, #3461b8 50%, #3d72d0 100%)' },
  { key: '학습성장', titleEn: 'Learning & Growth',  gradient: 'linear-gradient(120deg, #5b2d8a 0%, #7340b8 50%, #8a52d0 100%)' },
  { key: '운영지원', titleEn: 'Operations',          gradient: 'linear-gradient(120deg, #0d6080 0%, #0d7a9a 50%, #0e92b8 100%)' },
  { key: '전산관리', titleEn: 'IT Management',       gradient: 'linear-gradient(120deg, #0a6040 0%, #0d8050 50%, #10a060 100%)' },
] as const;

const STATUS_LABEL: Record<string, string> = {
  IN_PROGRESS: '진행',
  REVIEW:      '보류',
  TODO:        '대기',
  DONE:        '완료',
  CANCELLED:   '취소',
};

const STATUS_DOT: Record<string, string> = {
  IN_PROGRESS: 'bg-blue-500',
  REVIEW:      'bg-orange-400',
  TODO:        'bg-gray-300',
  DONE:        'bg-emerald-500',
  CANCELLED:   'bg-gray-300',
};

interface PanelColumnProps {
  section: typeof SECTIONS[number];
  tasks: Task[];
  label: string;
}

function PanelColumn({ section, tasks, label }: PanelColumnProps) {
  const issues = tasks.filter((t) => t.issueNote);

  return (
    <div className="flex flex-col h-full min-h-0 overflow-hidden">
      {/* 헤더 */}
      <div className="shrink-0 flex items-center h-10 px-4 gap-2"
        style={{ background: section.gradient }}>
        <span className="text-white font-black text-sm tracking-tight truncate">{label}</span>
        <span className="text-white/60 text-xs font-medium truncate hidden 2xl:block">{section.titleEn}</span>
        <span className="ml-auto shrink-0 text-xs font-black bg-white/20 text-white px-2 py-0.5 rounded-full">
          {tasks.length}건
        </span>
      </div>

      {/* 업무 목록 (flex 4) */}
      <div className="flex flex-col min-h-0" style={{ flex: 4 }}>
        <div className="px-3 py-1.5 border-b border-gray-100 shrink-0">
          <span className="text-xs font-black text-gray-400 uppercase tracking-wider">업무 내용</span>
        </div>
        <div className="flex-1 overflow-y-auto px-3 py-2 space-y-1">
          {tasks.length === 0 ? (
            <p className="text-xs text-gray-300 py-2 text-center">등록된 상시업무 없음</p>
          ) : (
            tasks.map((t) => (
              <div key={t.id}
                className="flex items-center gap-2 rounded-lg bg-white border border-gray-100 px-2.5 py-1.5 hover:border-gray-200 transition-all">
                <span className={`shrink-0 w-2 h-2 rounded-full ${STATUS_DOT[t.status] ?? 'bg-gray-300'}`} />
                <span className="flex-1 text-xs font-semibold text-gray-700 truncate">{t.title}</span>
                <span className="shrink-0 text-xs font-bold text-gray-400">{STATUS_LABEL[t.status]}</span>
                <div className="shrink-0 w-10 h-1.5 bg-gray-100 rounded-full overflow-hidden">
                  <div className={`h-1.5 rounded-full ${
                    t.progress >= 70 ? 'bg-emerald-400' :
                    t.progress >= 40 ? 'bg-blue-400' : 'bg-orange-400'
                  }`} style={{ width: `${t.progress}%` }} />
                </div>
              </div>
            ))
          )}
        </div>
      </div>

      {/* 이슈 (flex 1) */}
      <div className="flex flex-col min-h-0 border-t-2 border-red-100" style={{ flex: 1 }}>
        <div className="px-3 py-1 bg-red-50 shrink-0 flex items-center gap-1.5 border-b border-red-100">
          <span className="text-xs font-black text-red-400 uppercase tracking-wider">이슈</span>
          {issues.length > 0 && (
            <span className="text-xs font-black bg-red-400 text-white px-1.5 py-0.5 rounded-full leading-none">
              {issues.length}
            </span>
          )}
        </div>
        <div className="flex-1 overflow-y-auto px-3 py-1 space-y-1">
          {issues.length === 0 ? (
            <p className="text-xs text-gray-300 py-1 text-center">이슈 없음</p>
          ) : (
            issues.map((t) => (
              <div key={t.id}
                className="flex items-start gap-1.5 rounded-lg bg-red-50 border border-red-100 px-2.5 py-1.5">
                <span className="shrink-0 text-red-400 text-xs mt-0.5">▶</span>
                <div className="flex-1 min-w-0">
                  <p className="text-xs font-bold text-gray-600 truncate">{t.title}</p>
                  <p className="text-xs text-red-500 truncate">{t.issueNote}</p>
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
}

interface RoutinePanelProps {
  tasks: Task[];
}

export function RoutinePanel({ tasks }: RoutinePanelProps) {
  const { data: configs } = useQuery<{ key: string; title: string }[]>({
    queryKey: ['columns', 'all-routine'],
    queryFn: async () => {
      const results = await Promise.all(
        SECTIONS.map((s) =>
          apiClient.get(`/columns/${encodeURIComponent(s.key)}`).then((r) => ({ key: s.key, ...r.data })),
        ),
      );
      return results;
    },
    staleTime: 0,
  });

  const getLabel = (key: string) =>
    configs?.find((c) => c.key === key)?.title ?? key;

  return (
    <div className="grid grid-cols-4 h-full min-h-0 divide-x divide-gray-200">
      {SECTIONS.map((section) => (
        <PanelColumn
          key={section.key}
          section={section}
          tasks={tasks.filter((t) => t.section === section.key)}
          label={getLabel(section.key)}
        />
      ))}
    </div>
  );
}
