'use client';

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

import { useState, useEffect, useCallback, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Copy, Edit, GripVertical, Plus, Trash2, ExternalLink } from 'lucide-react';
import { ReorderButtons } from '@/components/molecules';
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 '@/stores/menuStore';
import { usePermission } from '@/hooks/usePermission';
import { toast } from 'sonner';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import { useDeleteDialog } from '@/hooks/useDeleteDialog';
import { getProcessSteps, reorderProcessSteps, removeProcessItem, deleteProcess, duplicateProcess } from './actions';
import type { Process, ProcessStep } from '@/types/process';

interface ProcessDetailProps {
  process: Process;
  onProcessUpdate?: (process: Process) => void;
}

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

  // 삭제 다이얼로그
  const deleteDialog = useDeleteDialog({
    onDelete: deleteProcess,
    onSuccess: () => router.push('/ko/master-data/process-management'),
    entityName: '공정',
  });

  // 단계 목록 상태
  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<HTMLElement | null>(null);

  // 개별 품목 목록 추출
  const individualItems = process.classificationRules
    .filter((r) => r.registrationType === 'individual')
    .flatMap((r) => r.items || []);
  const itemCount = individualItems.length;

  // 단계 목록 로드
  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 handleRemoveItem = async (itemId: string) => {
    const remainingIds = individualItems
      .filter((item) => item.id !== itemId)
      .map((item) => parseInt(item.id, 10));

    const result = await removeProcessItem(process.id, remainingIds);
    if (result.success && result.data) {
      toast.success('품목이 제거되었습니다.');
      onProcessUpdate?.(result.data);
    } else {
      toast.error(result.error || '품목 제거에 실패했습니다.');
    }
  };

  // 품목 전체 삭제
  const [showRemoveAllDialog, setShowRemoveAllDialog] = useState(false);
  const handleRemoveAllItems = async () => {
    const result = await removeProcessItem(process.id, []);
    if (result.success && result.data) {
      toast.success('품목이 모두 제거되었습니다.');
      onProcessUpdate?.(result.data);
    } else {
      toast.error(result.error || '품목 전체 제거에 실패했습니다.');
    }
    setShowRemoveAllDialog(false);
  };

  const [isDuplicating, setIsDuplicating] = useState(false);

  // 공정 복제
  const handleDuplicate = async () => {
    setIsDuplicating(true);
    const result = await duplicateProcess(process.id);
    setIsDuplicating(false);
    if (result.success && result.data) {
      toast.success('공정이 복제되었습니다.');
      router.push(`/ko/master-data/process-management/${result.data.id}?mode=view`);
    } else {
      toast.error(result.error || '공정 복제에 실패했습니다.');
    }
  };

  // 네비게이션
  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?mode=new`);
  };

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

  // ===== 드래그&드롭 (HTML5 네이티브) =====
  const handleDragStart = useCallback((e: React.DragEvent<HTMLElement>, 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<HTMLElement>, 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<HTMLElement>, 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);
      const reordered = updated.map((step, i) => ({ ...step, order: i + 1 }));

      // API 순서 변경 호출
      reorderProcessSteps(
        process.id,
        reordered.map((s) => ({ id: s.id, order: s.order }))
      );

      return reordered;
    });

    handleDragEnd();
  }, [dragIndex, handleDragEnd, process.id]);

  // 화살표 버튼으로 순서 변경
  const handleMoveStep = useCallback((fromIndex: number, toIndex: number) => {
    setSteps((prev) => {
      const updated = [...prev];
      const [moved] = updated.splice(fromIndex, 1);
      updated.splice(toIndex, 0, moved);
      const reordered = updated.map((step, i) => ({ ...step, order: i + 1 }));

      reorderProcessSteps(
        process.id,
        reordered.map((s) => ({ id: s.id, order: s.order }))
      );

      return reordered;
    });
  }, [process.id]);

  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">
            {/* Row 1: 공정번호 | 공정명 | 담당부서 | 담당자 */}
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 md: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>
                <div className="font-medium">{process.processName}</div>
              </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>
            {/* Row 2: 부모공정 | 구분 | 생산일자 | 상태 */}
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6 mt-4 md:mt-6">
              <div className="space-y-1">
                <div className="text-sm text-muted-foreground">부모 공정</div>
                {process.parentId ? (
                  <button
                    type="button"
                    onClick={() => router.push(`/ko/master-data/process-management/${process.parentId}?mode=view`)}
                    className="font-medium text-primary hover:underline flex items-center gap-1"
                  >
                    [{process.parentProcessCode}] {process.parentProcessName}
                    <ExternalLink className="h-3 w-3" />
                  </button>
                ) : (
                  <div className="font-medium text-muted-foreground">없음 (루트 공정)</div>
                )}
              </div>
              <div className="space-y-1">
                <div className="text-sm text-muted-foreground">구분</div>
                <div className="font-medium">{process.processCategory || '없음'}</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>
            {/* Row 3: 중간검사여부 | 중간검사양식 | 작업일지여부 | 작업일지양식 */}
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6 mt-4 md:mt-6">
              <div className="space-y-1">
                <div className="text-sm text-muted-foreground">중간검사 여부</div>
                <Badge variant={process.needsInspection ? 'default' : 'secondary'}>
                  {process.needsInspection ? '사용' : '미사용'}
                </Badge>
              </div>
              {process.needsInspection && (
                <div className="space-y-1">
                  <div className="text-sm text-muted-foreground">중간검사 양식</div>
                  <div className="font-medium">{process.documentTemplateName || '-'}</div>
                </div>
              )}
              <div className="space-y-1">
                <div className="text-sm text-muted-foreground">작업일지 여부</div>
                <Badge variant={process.needsWorkLog ? 'default' : 'secondary'}>
                  {process.needsWorkLog ? '사용' : '미사용'}
                </Badge>
              </div>
              {process.needsWorkLog && (
                <div className="space-y-1">
                  <div className="text-sm text-muted-foreground">작업일지 양식</div>
                  <div className="font-medium">{process.workLogTemplateName || '-'}</div>
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        {/* 하위 공정 (자식이 있을 때만 표시) */}
        {process.children && process.children.length > 0 && (
          <Card>
            <CardHeader className="bg-muted/50 py-3">
              <div className="flex items-center gap-2">
                <CardTitle className="text-base">하위 공정</CardTitle>
                <Badge variant="outline" className="text-xs">
                  {process.children.length}개
                </Badge>
              </div>
            </CardHeader>
            <CardContent className="p-0">
              <div className="divide-y">
                {process.children.map((child) => (
                  <div
                    key={child.id}
                    onClick={() => router.push(`/ko/master-data/process-management/${child.id}?mode=view`)}
                    className="flex items-center gap-4 px-4 py-3 cursor-pointer hover:bg-muted/50"
                  >
                    <span className="text-sm font-mono text-muted-foreground">{child.processCode}</span>
                    <span className="text-sm font-medium flex-1">{child.processName}</span>
                    <Badge variant={child.status === '사용중' ? 'default' : 'secondary'} className="text-xs">
                      {child.status === '사용중' ? '사용' : '미사용'}
                    </Badge>
                    <ExternalLink className="h-3.5 w-3.5 text-muted-foreground" />
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}

        {/* 품목 설정 정보 */}
        <Card>
          <CardHeader className="bg-muted/50 py-3">
            <div className="flex items-center gap-2 flex-wrap">
              <CardTitle className="text-base shrink-0">
                품목 설정 정보
              </CardTitle>
              <Badge variant="outline" className="text-xs">
                {itemCount}개
              </Badge>
              <Button variant="outline" size="sm" onClick={handleEdit} className="shrink-0">
                공정 품목 선택
              </Button>
              {itemCount > 0 && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setShowRemoveAllDialog(true)}
                  className="shrink-0 text-destructive hover:text-destructive"
                >
                  <Trash2 className="h-3.5 w-3.5 mr-1" />
                  전체 삭제
                </Button>
              )}
            </div>
            <p className="text-sm text-muted-foreground mt-1">
              품목을 선택하면 이 공정으로 분류됩니다
            </p>
          </CardHeader>
          {individualItems.length > 0 && (
            <CardContent className="pt-4 max-h-[240px] md:max-h-none overflow-y-auto">
              <div className="flex flex-wrap gap-1.5">
                {individualItems.map((item) => (
                  <div
                    key={item.id}
                    className="inline-flex items-center gap-1.5 rounded-full border bg-muted/30 pl-3 pr-1.5 py-1 text-xs"
                  >
                    <span className="font-mono">{item.code}</span>
                    <button
                      type="button"
                      onClick={() => handleRemoveItem(item.id)}
                      className="shrink-0 rounded-full p-0.5 text-muted-foreground/50 hover:text-destructive transition-colors"
                    >
                      <Trash2 className="h-3 w-3" />
                    </button>
                  </div>
                ))}
              </div>
            </CardContent>
          )}
        </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="md:hidden divide-y">
                {steps.map((step, index) => (
                  <div
                    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={`flex items-center gap-2 px-3 py-2.5 cursor-pointer hover:bg-muted/50 ${
                      dragOverIndex === index && dragIndex !== index
                        ? 'border-t-2 border-t-primary'
                        : ''
                    }`}
                  >
                    <ReorderButtons
                      onMoveUp={() => handleMoveStep(index, index - 1)}
                      onMoveDown={() => handleMoveStep(index, index + 1)}
                      isFirst={index === 0}
                      isLast={index === steps.length - 1}
                      size="xs"
                    />
                    <span className="text-xs text-muted-foreground w-5 shrink-0">{index + 1}</span>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-1.5">
                        <span className="text-xs font-mono text-muted-foreground">{step.stepCode}</span>
                        <span className="text-sm font-medium truncate">{step.stepName}</span>
                      </div>
                    </div>
                    <div className="flex items-center gap-1 shrink-0">
                      <Badge variant={step.isRequired ? 'default' : 'outline'} className="text-[10px] px-1.5 py-0">필수</Badge>
                      <Badge variant={step.needsApproval ? 'default' : 'outline'} className="text-[10px] px-1.5 py-0">승인</Badge>
                      <Badge variant={step.needsInspection ? 'default' : 'outline'} className="text-[10px] px-1.5 py-0">검사</Badge>
                    </div>
                  </div>
                ))}
              </div>
              {/* 데스크탑: 테이블 */}
              <div className="hidden md:block overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b bg-muted/30">
                      <th className="w-16 px-3 py-3 text-center text-xs font-medium text-muted-foreground" />
                      <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-16 px-3 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                          <div className="flex items-center justify-center gap-0.5">
                            <GripVertical className="h-4 w-4 text-muted-foreground cursor-grab active:cursor-grabbing" />
                            <ReorderButtons
                              onMoveUp={() => handleMoveStep(index, index - 1)}
                              onMoveDown={() => handleMoveStep(index, index + 1)}
                              isFirst={index === 0}
                              isLast={index === steps.length - 1}
                              size="xs"
                            />
                          </div>
                        </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-4 left-4 right-4 px-4 py-3 bg-background/95 backdrop-blur rounded-xl border shadow-lg z-50 transition-all duration-300 md:bottom-6 md:px-6 md:right-[48px] ${sidebarCollapsed ? 'md:left-[156px]' : 'md:left-[316px]'} flex items-center justify-between`}
      >
        <Button variant="outline" onClick={handleList} size="sm" className="md:size-default">
          <ArrowLeft className="h-4 w-4 md:mr-2" />
          <span className="hidden md:inline">목록으로</span>
        </Button>
        {canUpdate && (
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              onClick={() => deleteDialog.single.open(process.id)}
              size="sm"
              className="md:size-default text-destructive hover:text-destructive"
            >
              <Trash2 className="h-4 w-4 md:mr-2" />
              <span className="hidden md:inline">삭제</span>
            </Button>
            <Button
              variant="outline"
              onClick={handleDuplicate}
              disabled={isDuplicating}
              size="sm"
              className="md:size-default"
            >
              <Copy className="h-4 w-4 md:mr-2" />
              <span className="hidden md:inline">{isDuplicating ? '복사 중...' : '복사'}</span>
            </Button>
            <Button onClick={handleEdit} size="sm" className="md:size-default">
              <Edit className="h-4 w-4 md:mr-2" />
              <span className="hidden md:inline">수정</span>
            </Button>
          </div>
        )}
      </div>

      {/* 삭제 확인 다이얼로그 */}
      <DeleteConfirmDialog
        open={deleteDialog.single.isOpen}
        onOpenChange={deleteDialog.single.onOpenChange}
        onConfirm={deleteDialog.single.confirm}
        loading={deleteDialog.isPending}
        description="이 공정을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
      />

      {/* 품목 전체 삭제 확인 다이얼로그 */}
      <DeleteConfirmDialog
        open={showRemoveAllDialog}
        onOpenChange={setShowRemoveAllDialog}
        onConfirm={handleRemoveAllItems}
        description={`등록된 품목 ${itemCount}개를 모두 삭제하시겠습니까?`}
      />
    </PageLayout>
  );
}
