'use client';

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

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { SquarePen, Trash2 } from 'lucide-react';
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 { Alert, AlertDescription } from '@/components/ui/alert';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { AssigneeSelectModal } from './AssigneeSelectModal';
import { toast } from 'sonner';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
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 EditableItem extends WorkOrderItem {
  isEditing?: boolean;
  editQuantity?: number;
}

// Validation 에러 타입
interface ValidationErrors {
  [key: string]: string;
}

// 필드명 매핑
const FIELD_NAME_MAP: Record<string, string> = {
  processId: '공정',
  scheduledDate: '출고예정일',
};

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

  // 수정 가능 정보
  processId: number | null;
  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,
    scheduledDate: '',
    priority: 5,
    assignees: [],
    note: '',
  });
  const [isAssigneeModalOpen, setIsAssigneeModalOpen] = useState(false);
  const [deleteTargetItemId, setDeleteTargetItemId] = useState<string | null>(null);
  const [assigneeNames, setAssigneeNames] = useState<string[]>([]);
  const [validationErrors, setValidationErrors] = useState<ValidationErrors>({});
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, 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<EditableItem[]>([]);

  // 데이터 로드
  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,
          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 })) || [];
        if (orderItems.length === 0) {
          // 개발/테스트용 목업 데이터
          setItems([
            {
              id: 'mock-1',
              no: 1,
              status: 'waiting',
              productName: 'KWW503 (와이어)',
              floorCode: '-',
              specification: '8,260 X 8,350 mm',
              quantity: 500,
              unit: 'm',
              orderNodeId: null,
              orderNodeName: '',
            },
            {
              id: 'mock-2',
              no: 2,
              status: 'waiting',
              productName: '스크린 원단',
              floorCode: '-',
              specification: '1,200 X 2,400 mm',
              quantity: 100,
              unit: 'EA',
              orderNodeId: null,
              orderNodeName: '',
            },
          ]);
        } else {
          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: ValidationErrors = {};

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

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

    // 에러가 있으면 상태 업데이트 후 리턴
    if (Object.keys(errors).length > 0) {
      setValidationErrors(errors);
      window.scrollTo({ top: 0, behavior: 'smooth' });
      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) {
        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(`공정 단계 상태가 변경되었습니다.`);
  }, []);

  // 품목 수량 수정 시작
  const handleItemEditStart = useCallback((itemId: string) => {
    setItems(prev =>
      prev.map(item =>
        item.id === itemId
          ? { ...item, isEditing: true, editQuantity: item.quantity }
          : item
      )
    );
  }, []);

  // 품목 수량 변경
  const handleItemQuantityChange = useCallback((itemId: string, quantity: number) => {
    setItems(prev =>
      prev.map(item =>
        item.id === itemId ? { ...item, editQuantity: quantity } : item
      )
    );
  }, []);

  // 품목 수량 수정 저장
  const handleItemEditSave = useCallback((itemId: string) => {
    setItems(prev =>
      prev.map(item =>
        item.id === itemId
          ? { ...item, quantity: item.editQuantity || item.quantity, isEditing: false }
          : item
      )
    );
    // TODO: API 호출로 서버에 저장
    toast.success('수량이 수정되었습니다.');
  }, []);

  // 품목 수량 수정 취소
  const handleItemEditCancel = useCallback((itemId: string) => {
    setItems(prev =>
      prev.map(item =>
        item.id === itemId ? { ...item, isEditing: false } : item
      )
    );
  }, []);

  // 품목 삭제
  const handleItemDelete = useCallback((itemId: string) => {
    setDeleteTargetItemId(itemId);
  }, []);

  const handleItemDeleteConfirm = useCallback(() => {
    if (!deleteTargetItemId) return;
    setItems(prev => prev.filter(item => item.id !== deleteTargetItemId));
    // TODO: API 호출로 서버에서 삭제
    toast.success('품목이 삭제되었습니다.');
    setDeleteTargetItemId(null);
  }, [deleteTargetItemId]);

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

  // 폼 컨텐츠 렌더링 (기획서 4열 그리드)
  const renderFormContent = useCallback(() => (
    <div className="space-y-6">
        {/* Validation 에러 표시 */}
        {Object.keys(validationErrors).length > 0 && (
          <Alert className="bg-red-50 border-red-200">
            <AlertDescription className="text-red-900">
              <div className="flex items-start gap-2">
                <span className="text-lg">⚠️</span>
                <div className="flex-1">
                  <strong className="block mb-2">
                    입력 내용을 확인해주세요 ({Object.keys(validationErrors).length}개 오류)
                  </strong>
                  <ul className="space-y-1 text-sm">
                    {Object.entries(validationErrors).map(([field, message]) => {
                      const fieldName = FIELD_NAME_MAP[field] || field;
                      return (
                        <li key={field} className="flex items-start gap-1">
                          <span>•</span>
                          <span>
                            <strong>{fieldName}</strong>: {message}
                          </span>
                        </li>
                      );
                    })}
                  </ul>
                </div>
              </div>
            </AlertDescription>
          </Alert>
        )}

        {/* 기본 정보 (기획서 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>
              <Select
                value={formData.processId?.toString() || ''}
                onValueChange={(value) => setFormData({ ...formData, processId: parseInt(value) })}
                disabled={isLoadingProcesses}
              >
                <SelectTrigger className="bg-white">
                  <SelectValue placeholder={isLoadingProcesses ? '로딩 중...' : '공정 선택'} />
                </SelectTrigger>
                <SelectContent>
                  {processOptions.map((process) => (
                    <SelectItem key={process.id} value={process.id.toString()}>
                      {process.processName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </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}
                onChange={(e) => setFormData({ ...formData, projectName: e.target.value })}
                className="bg-white"
              />
            </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 })}
              />
            </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={workOrder?.department || '-'} disabled className="bg-muted" />
            </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 ? (
            <Table>
              <TableHeader>
                <TableRow className="bg-muted/50">
                  <TableHead>로트번호</TableHead>
                  <TableHead>품목명</TableHead>
                  <TableHead className="w-32 text-right">수량</TableHead>
                  <TableHead className="w-20">단위</TableHead>
                  <TableHead className="w-24 text-center">관리</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {items.map((item) => (
                  <TableRow key={item.id}>
                    <TableCell>{workOrder?.lotNo || '-'}</TableCell>
                    <TableCell className="font-medium">{item.productName}</TableCell>
                    <TableCell className="text-right">
                      {item.isEditing ? (
                        <div className="flex items-center gap-1 justify-end">
                          <Input
                            type="number"
                            value={item.editQuantity}
                            onChange={(e) =>
                              handleItemQuantityChange(item.id, parseInt(e.target.value) || 0)
                            }
                            className="w-20 h-8 text-right"
                            min={0}
                          />
                          <Button
                            type="button"
                            size="sm"
                            variant="ghost"
                            className="h-8 px-2 text-green-600 hover:text-green-700"
                            onClick={() => handleItemEditSave(item.id)}
                          >
                            ✓
                          </Button>
                          <Button
                            type="button"
                            size="sm"
                            variant="ghost"
                            className="h-8 px-2 text-gray-500 hover:text-gray-600"
                            onClick={() => handleItemEditCancel(item.id)}
                          >
                            ✕
                          </Button>
                        </div>
                      ) : (
                        item.quantity
                      )}
                    </TableCell>
                    <TableCell>{item.unit}</TableCell>
                    <TableCell>
                      <div className="flex items-center justify-center gap-1">
                        <Button
                          type="button"
                          size="sm"
                          variant="ghost"
                          className="h-8 w-8 p-0"
                          onClick={() => handleItemEditStart(item.id)}
                          disabled={item.isEditing}
                        >
                          <SquarePen className="h-4 w-4" />
                        </Button>
                        <Button
                          type="button"
                          size="sm"
                          variant="ghost"
                          className="h-8 w-8 p-0 text-red-500 hover:text-red-600"
                          onClick={() => handleItemDelete(item.id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          ) : (
            <p className="text-muted-foreground text-center py-8">
              등록된 품목이 없습니다.
            </p>
          )}
        </section>
      </div>
  ), [formData, validationErrors, processOptions, isLoadingProcesses, assigneeNames, workOrder, processSteps, stepStatus, items, handleStepToggle, handleItemEditStart, handleItemQuantityChange, handleItemEditSave, handleItemEditCancel, handleItemDelete]);

  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);
        }}
      />

      {/* 품목 삭제 확인 다이얼로그 */}
      <DeleteConfirmDialog
        open={deleteTargetItemId !== null}
        onOpenChange={(open) => !open && setDeleteTargetItemId(null)}
        onConfirm={handleItemDeleteConfirm}
        title="품목 삭제"
        description="이 품목을 삭제하시겠습니까?"
      />
    </>
  );
}