'use client';

/**
 * 공정 상세 페이지 (리디자인)
 *
 * 기획서 스크린샷 1 기준:
 * - 기본 정보: 공정번호, 공정형, 담당부서, 담당자, 생산일자, 상태
 * - 품목 설정 정보: 품목 선택 버튼 + 개수 표시
 * - 단계 테이블: 드래그&드롭 순서변경 + 단계 등록 버튼
 */

import { useState, useEffect, useCallback, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Edit, GripVertical, Plus, Package } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { useMenuStore } from '@/store/menuStore';
import { getProcessSteps } from './actions';
import type { Process, ProcessStep } from '@/types/process';

interface ProcessDetailProps {
  process: Process;
}

export function ProcessDetail({ process }: ProcessDetailProps) {
  const router = useRouter();
  const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);

  // 단계 목록 상태
  const [steps, setSteps] = useState<ProcessStep[]>([]);
  const [isStepsLoading, setIsStepsLoading] = useState(true);

  // 드래그 상태
  const [dragIndex, setDragIndex] = useState<number | null>(null);
  const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);
  const dragNodeRef = useRef<HTMLTableRowElement | null>(null);

  // 품목 개수 계산 (기존 classificationRules에서 individual 품목)
  const itemCount = process.classificationRules
    .filter((r) => r.registrationType === 'individual')
    .reduce((sum, r) => sum + (r.items?.length || 0), 0);

  // 단계 목록 로드
  useEffect(() => {
    const loadSteps = async () => {
      setIsStepsLoading(true);
      const result = await getProcessSteps(process.id);
      if (result.success && result.data) {
        setSteps(result.data);
      }
      setIsStepsLoading(false);
    };
    loadSteps();
  }, [process.id]);

  // 네비게이션
  const handleEdit = () => {
    router.push(`/ko/master-data/process-management/${process.id}?mode=edit`);
  };

  const handleList = () => {
    router.push('/ko/master-data/process-management');
  };

  const handleAddStep = () => {
    router.push(`/ko/master-data/process-management/${process.id}/steps/new`);
  };

  const handleStepClick = (stepId: string) => {
    router.push(`/ko/master-data/process-management/${process.id}/steps/${stepId}`);
  };

  // ===== 드래그&드롭 (HTML5 네이티브) =====
  const handleDragStart = useCallback((e: React.DragEvent<HTMLTableRowElement>, index: number) => {
    setDragIndex(index);
    dragNodeRef.current = e.currentTarget;
    e.dataTransfer.effectAllowed = 'move';
    // 약간의 딜레이로 드래그 시작 시 스타일 적용
    requestAnimationFrame(() => {
      if (dragNodeRef.current) {
        dragNodeRef.current.style.opacity = '0.4';
      }
    });
  }, []);

  const handleDragOver = useCallback((e: React.DragEvent<HTMLTableRowElement>, index: number) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
    setDragOverIndex(index);
  }, []);

  const handleDragEnd = useCallback(() => {
    if (dragNodeRef.current) {
      dragNodeRef.current.style.opacity = '1';
    }
    setDragIndex(null);
    setDragOverIndex(null);
    dragNodeRef.current = null;
  }, []);

  const handleDrop = useCallback((e: React.DragEvent<HTMLTableRowElement>, dropIndex: number) => {
    e.preventDefault();
    if (dragIndex === null || dragIndex === dropIndex) return;

    setSteps((prev) => {
      const updated = [...prev];
      const [moved] = updated.splice(dragIndex, 1);
      updated.splice(dropIndex, 0, moved);
      // 순서 재할당
      return updated.map((step, i) => ({ ...step, order: i + 1 }));
    });

    handleDragEnd();
  }, [dragIndex, handleDragEnd]);

  return (
    <PageLayout>
      {/* 헤더 */}
      <PageHeader title="공정 상세" />

      <div className="space-y-6 pb-24">
        {/* 기본 정보 */}
        <Card>
          <CardHeader className="bg-muted/50">
            <CardTitle className="text-base">기본 정보</CardTitle>
          </CardHeader>
          <CardContent className="pt-6">
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-6">
              <div className="space-y-1">
                <div className="text-sm text-muted-foreground">공정번호</div>
                <div className="font-medium">{process.processCode}</div>
              </div>
              <div className="space-y-1">
                <div className="text-sm text-muted-foreground">공정형</div>
                <Badge variant="secondary">{process.processType}</Badge>
              </div>
              <div className="space-y-1">
                <div className="text-sm text-muted-foreground">담당부서</div>
                <div className="font-medium">{process.department || '-'}</div>
              </div>
              <div className="space-y-1">
                <div className="text-sm text-muted-foreground">담당자</div>
                <div className="font-medium">{process.manager || '-'}</div>
              </div>
              <div className="space-y-1">
                <div className="text-sm text-muted-foreground">생산일자</div>
                <div className="font-medium">
                  {process.useProductionDate ? '사용' : '미사용'}
                </div>
              </div>
              <div className="space-y-1">
                <div className="text-sm text-muted-foreground">상태</div>
                <Badge variant={process.status === '사용중' ? 'default' : 'secondary'}>
                  {process.status}
                </Badge>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 품목 설정 정보 */}
        <Card>
          <CardHeader className="bg-muted/50">
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="text-base flex items-center gap-2">
                  <Package className="h-4 w-4" />
                  품목 설정 정보
                </CardTitle>
                <p className="text-sm text-muted-foreground mt-1">
                  품목을 선택하면 이 공정으로 분류됩니다
                </p>
              </div>
              <div className="flex items-center gap-3">
                <Badge variant="outline" className="text-sm">
                  {itemCount}개
                </Badge>
                <Button variant="outline" size="sm" onClick={handleEdit}>
                  품목 선택
                </Button>
              </div>
            </div>
          </CardHeader>
        </Card>

        {/* 단계 테이블 */}
        <Card>
          <CardHeader className="bg-muted/50">
            <div className="flex items-center justify-between">
              <CardTitle className="text-base">
                단계
                {!isStepsLoading && (
                  <span className="text-sm font-normal text-muted-foreground ml-2">
                    총 {steps.length}건
                  </span>
                )}
              </CardTitle>
              <Button size="sm" onClick={handleAddStep}>
                <Plus className="h-4 w-4 mr-1" />
                단계 등록
              </Button>
            </div>
          </CardHeader>
          <CardContent className="p-0">
            {isStepsLoading ? (
              <div className="p-8 text-center text-muted-foreground">
                로딩 중...
              </div>
            ) : steps.length === 0 ? (
              <div className="p-8 text-center text-muted-foreground">
                등록된 단계가 없습니다. [단계 등록] 버튼으로 추가해주세요.
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b bg-muted/30">
                      <th className="w-10 px-3 py-3 text-center text-xs font-medium text-muted-foreground">
                        {/* 드래그 핸들 헤더 */}
                      </th>
                      <th className="w-14 px-3 py-3 text-center text-xs font-medium text-muted-foreground">
                        No.
                      </th>
                      <th className="px-3 py-3 text-left text-xs font-medium text-muted-foreground">
                        단계코드
                      </th>
                      <th className="px-3 py-3 text-left text-xs font-medium text-muted-foreground">
                        단계명
                      </th>
                      <th className="w-20 px-3 py-3 text-center text-xs font-medium text-muted-foreground">
                        필수여부
                      </th>
                      <th className="w-20 px-3 py-3 text-center text-xs font-medium text-muted-foreground">
                        승인여부
                      </th>
                      <th className="w-20 px-3 py-3 text-center text-xs font-medium text-muted-foreground">
                        검사여부
                      </th>
                      <th className="w-16 px-3 py-3 text-center text-xs font-medium text-muted-foreground">
                        사용
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {steps.map((step, index) => (
                      <tr
                        key={step.id}
                        draggable
                        onDragStart={(e) => handleDragStart(e, index)}
                        onDragOver={(e) => handleDragOver(e, index)}
                        onDragEnd={handleDragEnd}
                        onDrop={(e) => handleDrop(e, index)}
                        onClick={() => handleStepClick(step.id)}
                        className={`border-b cursor-pointer transition-colors hover:bg-muted/50 ${
                          dragOverIndex === index && dragIndex !== index
                            ? 'border-t-2 border-t-primary'
                            : ''
                        }`}
                      >
                        <td
                          className="w-10 px-3 py-3 text-center cursor-grab active:cursor-grabbing"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <GripVertical className="h-4 w-4 text-muted-foreground mx-auto" />
                        </td>
                        <td className="w-14 px-3 py-3 text-center text-sm text-muted-foreground">
                          {index + 1}
                        </td>
                        <td className="px-3 py-3 text-sm font-mono">
                          {step.stepCode}
                        </td>
                        <td className="px-3 py-3 text-sm font-medium">
                          {step.stepName}
                        </td>
                        <td className="w-20 px-3 py-3 text-center">
                          <Badge
                            variant={step.isRequired ? 'default' : 'outline'}
                            className="text-xs"
                          >
                            {step.isRequired ? 'Y' : 'N'}
                          </Badge>
                        </td>
                        <td className="w-20 px-3 py-3 text-center">
                          <Badge
                            variant={step.needsApproval ? 'default' : 'outline'}
                            className="text-xs"
                          >
                            {step.needsApproval ? 'Y' : 'N'}
                          </Badge>
                        </td>
                        <td className="w-20 px-3 py-3 text-center">
                          <Badge
                            variant={step.needsInspection ? 'default' : 'outline'}
                            className="text-xs"
                          >
                            {step.needsInspection ? 'Y' : 'N'}
                          </Badge>
                        </td>
                        <td className="w-16 px-3 py-3 text-center">
                          <Badge
                            variant={step.isActive ? 'default' : 'secondary'}
                            className="text-xs"
                          >
                            {step.isActive ? 'Y' : 'N'}
                          </Badge>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* 하단 액션 버튼 (sticky) */}
      <div
        className={`fixed bottom-6 ${sidebarCollapsed ? 'left-[156px]' : 'left-[316px]'} right-[48px] px-6 py-3 bg-background/95 backdrop-blur rounded-xl border shadow-lg z-50 transition-all duration-300 flex items-center justify-between`}
      >
        <Button variant="outline" onClick={handleList}>
          <ArrowLeft className="h-4 w-4 mr-2" />
          목록으로
        </Button>
        <Button onClick={handleEdit}>
          <Edit className="h-4 w-4 mr-2" />
          수정
        </Button>
      </div>
    </PageLayout>
  );
}
