'use client';

/**
 * 담당자 선택 모달
 *
 * 팀별로 그룹화된 담당자를 다중 선택할 수 있는 모달
 */

import { useState, useEffect, useMemo } from 'react';
import { Check, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Dialog,
  DialogContent,
  DialogTitle,
} from '@/components/ui/dialog';
import { VisuallyHidden } from '@radix-ui/react-visually-hidden';

// 담당자 타입
interface Assignee {
  id: string;
  name: string;
  teamId: string;
}

// 팀 타입
interface Team {
  id: string;
  name: string;
  members: Assignee[];
}

// Mock 팀/담당자 데이터
const TEAMS: Team[] = [
  {
    id: 'screen',
    name: '스크린팀',
    members: [
      { id: 'a1', name: '김스크린', teamId: 'screen' },
      { id: 'a2', name: '이스크린', teamId: 'screen' },
      { id: 'a3', name: '박스크린', teamId: 'screen' },
    ],
  },
  {
    id: 'bending',
    name: '절곡팀',
    members: [
      { id: 'b1', name: '김절곡', teamId: 'bending' },
      { id: 'b2', name: '이철곡', teamId: 'bending' },
      { id: 'b3', name: '박철곡', teamId: 'bending' },
      { id: 'b4', name: '최철곡', teamId: 'bending' },
    ],
  },
  {
    id: 'slat',
    name: '슬랫팀',
    members: [
      { id: 'c1', name: '김슬랫', teamId: 'slat' },
      { id: 'c2', name: '이슬랫', teamId: 'slat' },
      { id: 'c3', name: '박슬랫', teamId: 'slat' },
    ],
  },
  {
    id: 'inventory',
    name: '재고(포장)팀',
    members: [
      { id: 'd1', name: '김포팀', teamId: 'inventory' },
      { id: 'd2', name: '이포팀', teamId: 'inventory' },
    ],
  },
];

interface AssigneeSelectModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  selectedIds: string[];
  onSelect: (ids: string[], names: string[]) => void;
}

export function AssigneeSelectModal({
  open,
  onOpenChange,
  selectedIds,
  onSelect,
}: AssigneeSelectModalProps) {
  const [localSelected, setLocalSelected] = useState<Set<string>>(new Set(selectedIds));

  // 모달 열릴 때 선택 상태 초기화
  useEffect(() => {
    if (open) {
      setLocalSelected(new Set(selectedIds));
    }
  }, [open, selectedIds]);

  // 전체 담당자 맵
  const assigneeMap = useMemo(() => {
    const map = new Map<string, Assignee>();
    TEAMS.forEach((team) => {
      team.members.forEach((member) => {
        map.set(member.id, member);
      });
    });
    return map;
  }, []);

  // 팀 전체 선택 여부 확인
  const isTeamFullySelected = (team: Team) => {
    return team.members.every((m) => localSelected.has(m.id));
  };

  // 팀 부분 선택 여부 확인
  const isTeamPartiallySelected = (team: Team) => {
    const selectedCount = team.members.filter((m) => localSelected.has(m.id)).length;
    return selectedCount > 0 && selectedCount < team.members.length;
  };

  // 개별 담당자 토글
  const toggleAssignee = (id: string) => {
    const newSelected = new Set(localSelected);
    if (newSelected.has(id)) {
      newSelected.delete(id);
    } else {
      newSelected.add(id);
    }
    setLocalSelected(newSelected);
  };

  // 팀 전체 토글
  const toggleTeam = (team: Team) => {
    const newSelected = new Set(localSelected);
    const isFullySelected = isTeamFullySelected(team);

    if (isFullySelected) {
      // 전체 선택 해제
      team.members.forEach((m) => newSelected.delete(m.id));
    } else {
      // 전체 선택
      team.members.forEach((m) => newSelected.add(m.id));
    }
    setLocalSelected(newSelected);
  };

  // 선택 완료
  const handleConfirm = () => {
    const ids = Array.from(localSelected);
    const names = ids.map((id) => assigneeMap.get(id)?.name || '').filter(Boolean);
    onSelect(ids, names);
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md p-0 gap-0">
        <VisuallyHidden>
          <DialogTitle>담당자 선택</DialogTitle>
        </VisuallyHidden>

        {/* 헤더 */}
        <div className="flex items-center justify-between px-6 py-4 border-b">
          <h2 className="text-lg font-semibold">담당자 선택</h2>
          <button
            type="button"
            onClick={() => onOpenChange(false)}
            className="rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100"
          >
            <X className="h-4 w-4" />
            <span className="sr-only">닫기</span>
          </button>
        </div>

        {/* 설명 텍스트 */}
        <p className="text-sm text-muted-foreground px-6 py-3">
          팀 전체 또는 개별 작업자를 선택할 수 있습니다
        </p>

        {/* 팀 목록 */}
        <div className="max-h-[400px] overflow-y-auto">
          {TEAMS.map((team) => (
            <div key={team.id}>
              {/* 팀 헤더 */}
              <div className="flex items-center justify-between px-6 py-4 border-b bg-white">
                <div className="flex items-center gap-3">
                  <Checkbox
                    id={`team-${team.id}`}
                    checked={isTeamFullySelected(team)}
                    className="h-5 w-5 rounded border-2"
                    data-state={
                      isTeamPartiallySelected(team)
                        ? 'indeterminate'
                        : isTeamFullySelected(team)
                        ? 'checked'
                        : 'unchecked'
                    }
                    onCheckedChange={() => toggleTeam(team)}
                  />
                  <label
                    htmlFor={`team-${team.id}`}
                    className="flex items-center gap-2 cursor-pointer"
                  >
                    <span className="text-muted-foreground">👥</span>
                    <span className="font-semibold">{team.name}</span>
                    <span className="text-muted-foreground">({team.members.length}명)</span>
                  </label>
                </div>
                <button
                  type="button"
                  onClick={() => toggleTeam(team)}
                  className="text-sm text-muted-foreground hover:text-foreground"
                >
                  팀 전체 선택
                </button>
              </div>

              {/* 팀 멤버 */}
              {team.members.map((member) => (
                <div
                  key={member.id}
                  className="flex items-center gap-3 px-6 py-4 border-b ml-8"
                >
                  <Checkbox
                    id={`member-${member.id}`}
                    checked={localSelected.has(member.id)}
                    className="h-5 w-5 rounded border-2"
                    onCheckedChange={() => toggleAssignee(member.id)}
                  />
                  <label
                    htmlFor={`member-${member.id}`}
                    className="flex items-center gap-2 cursor-pointer"
                  >
                    <span className="text-muted-foreground">👤</span>
                    <span>{member.name}</span>
                  </label>
                </div>
              ))}
            </div>
          ))}
        </div>

        {/* 하단 버튼 */}
        <div className="px-6 py-4">
          <Button onClick={handleConfirm} className="w-full bg-black hover:bg-black/90">
            <Check className="w-4 h-4 mr-1.5" />
            선택 완료 ({localSelected.size}명)
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}