'use client';

/**
 * 작업지시 수정 페이지
 * WorkOrderCreate 패턴 기반
 * IntegratedDetailTemplate 마이그레이션 (2025-01-20)
 * 공정 진행 토글 + 품목 테이블 추가 (2026-02-05)
 */

import React, { useState, useEffect, useCallback } from 'react';
import { invalidateDashboard } from '@/lib/dashboard-invalidation';
import { useRouter } from 'next/navigation';
import { Input } from '@/components/ui/input';
import { DatePicker } from '@/components/ui/date-picker';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { AssigneeSelectModal } from './AssigneeSelectModal';
import { toast } from 'sonner';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { getWorkOrderById, updateWorkOrder, getProcessOptions, type ProcessOption } from './actions';
import type { WorkOrder, WorkOrderItem, ProcessStep } from './types';
import { SCREEN_PROCESS_STEPS } from './types';
import { workOrderEditConfig } from './workOrderConfig';

// 공정 단계 완료 상태 타입
interface ProcessStepStatus {
  [key: string]: boolean;
}


interface FormData {
  // 기본 정보 (읽기 전용)
  client: string;
  projectName: string;
  orderNo: string;
  itemCount: number;

  // 수정 가능 정보
  processId: number | null;
  department: string;
  scheduledDate: string;
  priority: number;
  assignees: string[];

  // 비고
  note: string;
}

interface WorkOrderEditProps {
  orderId: string;
}

export function WorkOrderEdit({ orderId }: WorkOrderEditProps) {
  const router = useRouter();
  const [workOrder, setWorkOrder] = useState<WorkOrder | null>(null);
  const [formData, setFormData] = useState<FormData>({
    client: '',
    projectName: '',
    orderNo: '',
    itemCount: 0,
    processId: null,
    department: '',
    scheduledDate: '',
    priority: 5,
    assignees: [],
    note: '',
  });
  const [isAssigneeModalOpen, setIsAssigneeModalOpen] = useState(false);
  const [assigneeNames, setAssigneeNames] = useState<string[]>([]);
  const [validationErrors, setValidationErrors] = useState<Record<string, string>>({});
  const [isLoading, setIsLoading] = useState(true);
  const [, setIsSubmitting] = useState(false);
  const [processOptions, setProcessOptions] = useState<ProcessOption[]>([]);
  const [isLoadingProcesses, setIsLoadingProcesses] = useState(true);

  // 공정 진행 상태
  const [processSteps, setProcessSteps] = useState<ProcessStep[]>([]);
  const [stepStatus, setStepStatus] = useState<ProcessStepStatus>({});

  // 품목 목록 (수정 가능)
  const [items, setItems] = useState<WorkOrderItem[]>([]);

  // 데이터 로드
  const loadData = useCallback(async () => {
    setIsLoading(true);
    try {
      const [orderResult, processResult] = await Promise.all([
        getWorkOrderById(orderId),
        getProcessOptions(),
      ]);

      if (orderResult.success && orderResult.data) {
        const order = orderResult.data;
        setWorkOrder(order);
        setFormData({
          client: order.client,
          projectName: order.projectName,
          orderNo: order.lotNo,
          itemCount: order.items?.length || 0,
          processId: order.processId,
          department: order.department || '',
          scheduledDate: order.scheduledDate || '',
          priority: order.priority || 5,
          assignees: order.assignees?.map(a => a.id) || [],
          note: order.note || '',
        });
        // 담당자 이름 설정
        if (order.assignees) {
          setAssigneeNames(order.assignees.map(a => a.name));
        }
        // 공정 단계 설정 (동적 또는 하드코딩 폴백)
        const steps = order.workSteps && order.workSteps.length > 0
          ? order.workSteps
          : SCREEN_PROCESS_STEPS;
        setProcessSteps(steps);
        // 공정 단계 완료 상태 초기화 (currentStep 기준)
        const initialStatus: ProcessStepStatus = {};
        steps.forEach((step, idx) => {
          initialStatus[step.key] = idx < order.currentStep;
        });
        setStepStatus(initialStatus);
        // 품목 목록 설정
        const orderItems = order.items?.map(item => ({ ...item })) || [];
        setItems(orderItems);
      } else {
        toast.error(orderResult.error || '작업지시 조회에 실패했습니다.');
        router.push('/production/work-orders');
        return;
      }

      if (processResult.success) {
        setProcessOptions(processResult.data);
      } else {
        toast.error(processResult.error || '공정 목록을 불러오는데 실패했습니다.');
      }
      setIsLoadingProcesses(false);
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('[WorkOrderEdit] loadData error:', error);
      toast.error('데이터 로드 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, [orderId, router]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  // 폼 제출
  const handleSubmit = async (): Promise<{ success: boolean; error?: string }> => {
    // Validation 체크
    const errors: Record<string, string> = {};

    if (!formData.processId) {
      errors.processId = '공정을 선택해주세요';
    }

    if (!formData.scheduledDate) {
      errors.scheduledDate = '출고예정일을 선택해주세요';
    }

    // 에러가 있으면 상태 업데이트 후 리턴
    if (Object.keys(errors).length > 0) {
      setValidationErrors(errors);
      const firstError = Object.values(errors)[0];
      toast.error(firstError);
      return { success: false, error: '입력 정보를 확인해주세요.' };
    }

    // 에러 초기화
    setValidationErrors({});
    setIsSubmitting(true);

    try {
      // 담당자 ID 배열 변환 (string[] → number[])
      const assigneeIds = formData.assignees
        .map(id => parseInt(id, 10))
        .filter(id => !isNaN(id));

      const result = await updateWorkOrder(orderId, {
        projectName: formData.projectName,
        processId: formData.processId!,
        scheduledDate: formData.scheduledDate,
        priority: formData.priority,
        assigneeIds: assigneeIds.length > 0 ? assigneeIds : undefined,
        note: formData.note || undefined,
      });

      if (result.success) {
        invalidateDashboard('production');
        toast.success('작업지시가 수정되었습니다.');
        router.push(`/production/work-orders/${orderId}?mode=view`);
        return { success: true };
      } else {
        return { success: false, error: result.error || '작업지시 수정에 실패했습니다.' };
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('[WorkOrderEdit] handleSubmit error:', error);
      return { success: false, error: '작업지시 수정 중 오류가 발생했습니다.' };
    } finally {
      setIsSubmitting(false);
    }
  };

  // 취소
  const handleCancel = () => {
    router.back();
  };

  // 공정 단계 토글
  const handleStepToggle = useCallback((stepKey: string) => {
    setStepStatus(prev => ({
      ...prev,
      [stepKey]: !prev[stepKey],
    }));
    // TODO: API 호출로 서버에 상태 저장
    toast.success(`공정 단계 상태가 변경되었습니다.`);
  }, []);

  // (품목 테이블은 읽기전용 — 수정/삭제 기능 제거됨)

  // 동적 config (작업지시 번호 포함)
  const dynamicConfig = {
    ...workOrderEditConfig,
    title: workOrder ? `작업지시 (${workOrder.workOrderNo})` : '작업지시',
  };

  // 폼 컨텐츠 렌더링 (기획서 4열 그리드)
  const renderFormContent = useCallback(() => (
    <div className="space-y-6">
        {/* 기본 정보 (기획서 4열 구성) */}
        <section className="bg-amber-50 border border-amber-200 rounded-lg p-4 md:p-6">
          <h3 className="font-semibold mb-4">기본 정보</h3>
          <div className="max-h-[400px] overflow-y-auto md:max-h-none md:overflow-visible">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-x-4 md:gap-x-6 gap-y-3 md:gap-y-4">
            {/* 1행: 작업번호(읽기) | 수주일(읽기) | 공정(셀렉트) | 구분(읽기) */}
            <div className="space-y-1">
              <Label className="text-sm text-muted-foreground">작업번호</Label>
              <Input value={workOrder?.workOrderNo || '-'} disabled className="bg-muted" />
            </div>
            <div className="space-y-1">
              <Label className="text-sm text-muted-foreground">수주일</Label>
              <Input value={workOrder?.salesOrderDate || '-'} disabled className="bg-muted" />
            </div>
            <div className="space-y-1">
              <Label className="text-sm text-muted-foreground">공정</Label>
              <Input
                value={processOptions.find(p => p.id === formData.processId)?.processName || workOrder?.processName || '-'}
                disabled
                className="bg-muted"
              />
            </div>
            <div className="space-y-1">
              <Label className="text-sm text-muted-foreground">구분</Label>
              <Input value="-" disabled className="bg-muted" />
            </div>

            {/* 2행: 로트번호(읽기) | 수주처(읽기) | 현장명(입력) | 수주 담당자(읽기) */}
            <div className="space-y-1">
              <Label className="text-sm text-muted-foreground">로트번호</Label>
              <Input value={formData.orderNo || '-'} disabled className="bg-muted" />
            </div>
            <div className="space-y-1">
              <Label className="text-sm text-muted-foreground">수주처</Label>
              <Input value={formData.client} disabled className="bg-muted" />
            </div>
            <div className="space-y-1">
              <Label className="text-sm text-muted-foreground">현장명</Label>
              <Input value={formData.projectName || '-'} disabled className="bg-muted" />
            </div>
            <div className="space-y-1">
              <Label className="text-sm text-muted-foreground">수주 담당자</Label>
              <Input value="-" disabled className="bg-muted" />
            </div>

            {/* 3행: 담당자 연락처(읽기) | 출고예정일(입력) | 틀수(읽기) | 우선순위(셀렉트) */}
            <div className="space-y-1">
              <Label className="text-sm text-muted-foreground">담당자 연락처</Label>
              <Input value="-" disabled className="bg-muted" />
            </div>
            <div className="space-y-1">
              <Label className="text-sm text-muted-foreground">출고예정일 *</Label>
              <DatePicker
                value={formData.scheduledDate}
                onChange={(date) => {
                  setFormData({ ...formData, scheduledDate: date });
                  if (validationErrors.scheduledDate) {
                    setValidationErrors(prev => { const { scheduledDate: _, ...rest } = prev; return rest; });
                  }
                }}
                className={validationErrors.scheduledDate ? 'border-red-500' : ''}
              />
              {validationErrors.scheduledDate && <p className="text-sm text-red-500">{validationErrors.scheduledDate}</p>}
            </div>
            <div className="space-y-1">
              <Label className="text-sm text-muted-foreground">틀수</Label>
              <Input value={workOrder?.shutterCount ?? '-'} disabled className="bg-muted" />
            </div>
            <div className="space-y-1">
              <Label className="text-sm text-muted-foreground">우선순위</Label>
              <Select
                value={formData.priority.toString()}
                onValueChange={(value) => setFormData({ ...formData, priority: parseInt(value) })}
              >
                <SelectTrigger className="bg-white">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {[1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => (
                    <SelectItem key={n} value={n.toString()}>
                      {n} {n <= 3 ? '(긴급)' : n <= 6 ? '(우선)' : '(일반)'}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 4행: 부서(읽기) | 생산 담당자(선택) | 상태(읽기) | 비고(입력) */}
            <div className="space-y-1">
              <Label className="text-sm text-muted-foreground">부서</Label>
              <Input
                value={formData.department}
                onChange={(e) => setFormData({ ...formData, department: e.target.value })}
                className="bg-white"
                placeholder="부서명 입력"
              />
            </div>
            <div className="space-y-1">
              <Label className="text-sm text-muted-foreground">생산 담당자</Label>
              <div
                onClick={() => setIsAssigneeModalOpen(true)}
                className="flex min-h-10 w-full cursor-pointer items-center rounded-md border border-input bg-white px-3 py-2 text-sm ring-offset-background hover:bg-accent/50"
              >
                {assigneeNames.length > 0 ? (
                  <span>{assigneeNames.join(', ')}</span>
                ) : (
                  <span className="text-muted-foreground">담당자 선택</span>
                )}
              </div>
            </div>
            <div className="space-y-1">
              <Label className="text-sm text-muted-foreground">상태</Label>
              <Input value={workOrder ? (workOrder.status === 'waiting' ? '작업대기' : workOrder.status === 'in_progress' ? '작업중' : workOrder.status === 'completed' ? '작업완료' : workOrder.status) : '-'} disabled className="bg-muted" />
            </div>
            <div className="space-y-1">
              <Label className="text-sm text-muted-foreground">비고</Label>
              <Textarea
                value={formData.note}
                onChange={(e) => setFormData({ ...formData, note: e.target.value })}
                placeholder="특이사항이나 메모를 입력하세요"
                rows={2}
                className="bg-white"
              />
            </div>
          </div>
          </div>
        </section>

        {/* 공정 진행 섹션 */}
        <section className="bg-white border rounded-lg p-6">
          <h3 className="font-semibold mb-4">공정 진행</h3>

          {/* 품목 정보 헤더 + 공정 단계 토글 */}
          <div className="border rounded-lg p-4 mb-6">
            {/* 품목 정보 헤더 */}
            <p className="font-semibold mb-3">
              {items.length > 0 ? (
                <>
                  {items[0].productName}
                  {items[0].specification !== '-' ? `  ${items[0].specification}` : ''}
                  {`  ${items[0].quantity}${items[0].unit !== '-' ? items[0].unit : '개'}`}
                </>
              ) : (
                <>
                  {workOrder?.processCode} ({workOrder?.processName})
                </>
              )}
            </p>

            {/* 공정 단계 토글 버튼 */}
            <div className="flex flex-col sm:flex-row sm:flex-wrap gap-2">
              {processSteps.map((step) => {
                const isCompleted = stepStatus[step.key] || false;
                return (
                  <button
                    key={step.key}
                    type="button"
                    onClick={() => handleStepToggle(step.key)}
                    className={`flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${
                      isCompleted
                        ? 'bg-emerald-500 text-white hover:bg-emerald-600'
                        : 'bg-gray-800 text-white hover:bg-gray-700'
                    }`}
                  >
                    <span>{step.label}</span>
                    {isCompleted && <span className="font-semibold">완료</span>}
                  </button>
                );
              })}
            </div>
          </div>

          {/* 작업 품목 - 개소별 그룹 */}
          {items.length > 0 ? (
            <div className="space-y-6">
              {/* 개소별 품목 그룹 */}
              <div>
                <h4 className="text-sm font-semibold text-muted-foreground mb-2">개소별 품목</h4>
                <Table>
                  <TableHeader>
                    <TableRow className="bg-muted/50">
                      <TableHead className="w-36">개소</TableHead>
                      <TableHead>품목명</TableHead>
                      <TableHead className="w-24 text-right">수량</TableHead>
                      <TableHead className="w-20">단위</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {(() => {
                      const nodeGroups = new Map<string, { label: string; items: WorkOrderItem[] }>();
                      for (const item of items) {
                        const floorLabel = item.floorCode !== '-' ? item.floorCode : '';
                        const key = item.orderNodeId != null ? String(item.orderNodeId) : (floorLabel || 'none');
                        const label = floorLabel || item.orderNodeName || `개소 ${nodeGroups.size + 1}`;
                        if (!nodeGroups.has(key)) {
                          nodeGroups.set(key, { label, items: [] });
                        }
                        nodeGroups.get(key)!.items.push(item);
                      }
                      const rows: React.ReactNode[] = [];
                      for (const [key, group] of nodeGroups) {
                        group.items.forEach((item, idx) => {
                          rows.push(
                            <TableRow key={`node-${key}-${item.id}`} className={idx === 0 ? 'border-t-2' : ''}>
                              {idx === 0 && (
                                <TableCell rowSpan={group.items.length} className="align-top font-medium bg-muted/30">
                                  {group.label}
                                </TableCell>
                              )}
                              <TableCell>{item.productName}</TableCell>
                              <TableCell className="text-right">{item.quantity}</TableCell>
                              <TableCell>{item.unit}</TableCell>
                            </TableRow>
                          );
                        });
                      }
                      return rows;
                    })()}
                  </TableBody>
                </Table>
              </div>

              {/* 품목별 합산 그룹 */}
              <div>
                <h4 className="text-sm font-semibold text-muted-foreground mb-2">품목별 합산</h4>
                <Table>
                  <TableHeader>
                    <TableRow className="bg-muted/50">
                      <TableHead className="w-12 text-center">No</TableHead>
                      <TableHead>품목명</TableHead>
                      <TableHead className="w-24 text-right">합산수량</TableHead>
                      <TableHead className="w-20">단위</TableHead>
                      <TableHead className="w-20 text-right">개소수</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {(() => {
                      const itemMap = new Map<string, { productName: string; totalQty: number; unit: string; nodeCount: number }>();
                      for (const item of items) {
                        const key = `${item.productName}||${item.unit}`;
                        if (!itemMap.has(key)) {
                          itemMap.set(key, { productName: item.productName, totalQty: 0, unit: item.unit, nodeCount: 0 });
                        }
                        const entry = itemMap.get(key)!;
                        entry.totalQty += Number(item.quantity);
                        entry.nodeCount += 1;
                      }
                      let no = 0;
                      return Array.from(itemMap.values()).map((entry) => {
                        no++;
                        return (
                          <TableRow key={`sum-${entry.productName}-${entry.unit}`}>
                            <TableCell className="text-center">{no}</TableCell>
                            <TableCell className="font-medium">{entry.productName}</TableCell>
                            <TableCell className="text-right">{entry.totalQty}</TableCell>
                            <TableCell>{entry.unit}</TableCell>
                            <TableCell className="text-right">{entry.nodeCount}</TableCell>
                          </TableRow>
                        );
                      });
                    })()}
                  </TableBody>
                </Table>
              </div>
            </div>
          ) : (
            <p className="text-muted-foreground text-center py-8">
              등록된 품목이 없습니다.
            </p>
          )}
        </section>
      </div>
  ), [formData, validationErrors, processOptions, isLoadingProcesses, assigneeNames, workOrder, processSteps, stepStatus, items, handleStepToggle]);

  return (
    <>
      <IntegratedDetailTemplate
        config={dynamicConfig}
        mode="edit"
        isLoading={isLoading}
        onCancel={handleCancel}
        onSubmit={async (_data: Record<string, unknown>) => {
          return handleSubmit();
        }}
        renderForm={renderFormContent}
      />

      {/* 담당자 선택 모달 */}
      <AssigneeSelectModal
        open={isAssigneeModalOpen}
        onOpenChange={setIsAssigneeModalOpen}
        selectedIds={formData.assignees}
        onSelect={(ids, names) => {
          setFormData({ ...formData, assignees: ids });
          setAssigneeNames(names);
        }}
      />

    </>
  );
}
