import { useEffect, useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { apiClient } from '../../lib/apiClient';
import {
  columnDisplayTitle,
  columnDisplayTitleEn,
  type BoardSlotConfig,
} from '../../lib/boardLayout';
import { isProjectTask } from '../../lib/taskType';
import { DeptIcon } from '../dashboard/DeptIcon';
import { TaskCard } from '../dashboard/TaskCard';
import { DeptProjectList } from '../dashboard/DeptProjectList';
import type { Task } from '../../types';

const SLOT_COUNT = 3;

const DUMMY_HEADER_KEY = 'eene-board-slot-headers-v1';

type DummyHeaders = Record<string, { title: string; titleEn: string; subtitle: string }>;

function loadDummyHeaders(): DummyHeaders {
  try {
    const raw = localStorage.getItem(DUMMY_HEADER_KEY);
    return raw ? JSON.parse(raw) : {};
  } catch {
    return {};
  }
}

interface DummyDepartmentColumnProps {
  slot: BoardSlotConfig;
  tasks: Task[];
  orderedIds: string[];
}

export function DummyDepartmentColumn({ slot, tasks, orderedIds }: DummyDepartmentColumnProps) {
  const isDummySlot = !slot.sectionKey;

  const { data: colConfig } = useQuery({
    queryKey: ['columns', slot.sectionKey],
    queryFn: () => apiClient.get(`/columns/${encodeURIComponent(slot.sectionKey!)}`).then((r) => r.data),
    enabled: !!slot.sectionKey,
    staleTime: 0,
  });

  const [dummyHeader, setDummyHeader] = useState(() => loadDummyHeaders()[slot.id]);

  useEffect(() => {
    setDummyHeader(loadDummyHeaders()[slot.id]);
  }, [slot.id]);

  const title = columnDisplayTitle(slot, colConfig, dummyHeader);
  const titleEnState = columnDisplayTitleEn(slot, colConfig, dummyHeader);
  const subtitle = isDummySlot ? dummyHeader?.subtitle ?? '' : colConfig?.subtitle ?? '';

  const projectTasks = useMemo(() => {
    const ordered = [...tasks].sort((a, b) => {
      const ai = orderedIds.indexOf(a.id);
      const bi = orderedIds.indexOf(b.id);
      if (ai === -1 && bi === -1) return 0;
      if (ai === -1) return 1;
      if (bi === -1) return -1;
      return ai - bi;
    });
    return ordered.filter((t) => isProjectTask(t.taskType)).slice(0, SLOT_COUNT);
  }, [tasks, orderedIds]);

  return (
    <section className={`dept-card ${slot.cssClass}`}>
      <div className="dept-head">
        <div className="dept-head-main">
          <DeptIcon slotId={slot.id} />
          <div className="board-dept-header-main">
            <div className="board-dept-title-wrap">
              <span className="board-dept-title" role="heading" aria-level={2}>
                {title.replace(/\s*부문$/, '')}
              </span>
              {titleEnState && <span className="board-dept-title-en">{titleEnState}</span>}
              <div className="dept-head-count" aria-label={`${projectTasks.length}건`}>
                <span className="poly-stat-val">{projectTasks.length}</span>
                <span className="poly-stat-unit">건</span>
              </div>
            </div>
            {subtitle && <p className="board-dept-subtitle">{subtitle}</p>}
          </div>
        </div>
      </div>

      <DeptProjectList
        items={projectTasks}
        getKey={(task) => task.id}
        renderItem={(task) => <TaskCard key={task.id} task={task} variant="project" />}
      />
    </section>
  );
}
