'use client';

/**
 * 공정 등록/수정 폼 컴포넌트
 * IntegratedDetailTemplate 마이그레이션 (2025-01-20)
 */

import { useState, useCallback, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Plus, Wrench, Trash2, Pencil } from 'lucide-react';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { processCreateConfig, processEditConfig } from './processConfig';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { QuantityInput } from '@/components/ui/quantity-input';
import { Checkbox } from '@/components/ui/checkbox';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { RuleModal } from './RuleModal';
import { toast } from 'sonner';
import type { Process, ClassificationRule, ProcessType } from '@/types/process';
import { PROCESS_TYPE_OPTIONS, MATCHING_TYPE_OPTIONS } from '@/types/process';
import { createProcess, updateProcess, getDepartmentOptions, type DepartmentOption } from './actions';

// 작업일지 양식 옵션 (추후 API 연동 가능)
const WORK_LOG_OPTIONS = [
  { value: '스크린 작업일지', label: '스크린 작업일지' },
  { value: '절곡 작업일지', label: '절곡 작업일지' },
  { value: '슬랫 작업일지', label: '슬랫 작업일지' },
  { value: '재고생산 작업일지', label: '재고생산 작업일지' },
  { value: '포장 작업일지', label: '포장 작업일지' },
];

interface ProcessFormProps {
  mode: 'create' | 'edit';
  initialData?: Process;
}

export function ProcessForm({ mode, initialData }: ProcessFormProps) {
  const router = useRouter();
  const isEdit = mode === 'edit';

  // 폼 상태
  const [processName, setProcessName] = useState(initialData?.processName || '');
  const [processType, setProcessType] = useState<ProcessType>(
    initialData?.processType || '생산'
  );
  const [department, setDepartment] = useState(initialData?.department || '');
  const [workLogTemplate, setWorkLogTemplate] = useState(
    initialData?.workLogTemplate || ''
  );
  const [classificationRules, setClassificationRules] = useState<ClassificationRule[]>(
    initialData?.classificationRules || []
  );
  const [requiredWorkers, setRequiredWorkers] = useState(
    initialData?.requiredWorkers || 1
  );
  const [equipmentInfo, setEquipmentInfo] = useState(initialData?.equipmentInfo || '');
  const [workSteps, setWorkSteps] = useState(initialData?.workSteps?.join(', ') || '');
  const [note, setNote] = useState(initialData?.note || '');
  const [isActive, setIsActive] = useState(initialData ? initialData.status === '사용중' : true);
  const [isLoading, setIsLoading] = useState(false);

  // 부서 목록 상태
  const [departmentOptions, setDepartmentOptions] = useState<DepartmentOption[]>([]);
  const [isDepartmentsLoading, setIsDepartmentsLoading] = useState(true);

  // 규칙 모달 상태
  const [ruleModalOpen, setRuleModalOpen] = useState(false);
  const [editingRule, setEditingRule] = useState<ClassificationRule | undefined>(undefined);

  // 부서 목록 로드
  useEffect(() => {
    const loadDepartments = async () => {
      setIsDepartmentsLoading(true);
      const departments = await getDepartmentOptions();
      setDepartmentOptions(departments);
      setIsDepartmentsLoading(false);
    };
    loadDepartments();
  }, []);

  // 규칙 추가/수정
  const handleSaveRule = useCallback(
    (ruleData: Omit<ClassificationRule, 'id' | 'createdAt'>) => {
      if (editingRule) {
        // 수정 모드
        setClassificationRules((prev) =>
          prev.map((r) =>
            r.id === editingRule.id
              ? { ...r, ...ruleData }
              : r
          )
        );
      } else {
        // 추가 모드
        const newRule: ClassificationRule = {
          ...ruleData,
          id: `rule-${Date.now()}`,
          createdAt: new Date().toISOString(),
        };
        setClassificationRules((prev) => [...prev, newRule]);
      }
      setEditingRule(undefined);
    },
    [editingRule]
  );

  // 규칙 수정 모달 열기
  const handleEditRule = useCallback((rule: ClassificationRule) => {
    setEditingRule(rule);
    setRuleModalOpen(true);
  }, []);

  // 규칙 삭제
  const handleDeleteRule = useCallback((ruleId: string) => {
    setClassificationRules((prev) => prev.filter((r) => r.id !== ruleId));
  }, []);

  // 모달 닫기
  const handleModalClose = useCallback((open: boolean) => {
    setRuleModalOpen(open);
    if (!open) {
      setEditingRule(undefined);
    }
  }, []);

  // 제출
  const handleSubmit = async () => {
    if (!processName.trim()) {
      toast.error('공정명을 입력해주세요.');
      return;
    }
    if (!department) {
      toast.error('담당부서를 선택해주세요.');
      return;
    }

    const formData = {
      processName: processName.trim(),
      processType,
      department,
      workLogTemplate: workLogTemplate || undefined,
      classificationRules: classificationRules.map((rule) => ({
        registrationType: rule.registrationType,
        ruleType: rule.ruleType,
        matchingType: rule.matchingType,
        conditionValue: rule.conditionValue,
        priority: rule.priority,
        description: rule.description,
        isActive: rule.isActive,
      })),
      requiredWorkers,
      equipmentInfo: equipmentInfo.trim() || undefined,
      workSteps: workSteps,
      note: note.trim() || undefined,
      isActive,
    };

    setIsLoading(true);
    try {
      if (isEdit && initialData?.id) {
        const result = await updateProcess(initialData.id, formData);
        if (result.success) {
          toast.success('공정이 수정되었습니다.');
          router.push('/ko/master-data/process-management');
        } else {
          toast.error(result.error || '수정에 실패했습니다.');
        }
      } else {
        const result = await createProcess(formData);
        if (result.success) {
          toast.success('공정이 등록되었습니다.');
          router.push('/ko/master-data/process-management');
        } else {
          toast.error(result.error || '등록에 실패했습니다.');
        }
      }
    } catch {
      toast.error('처리 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  };

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

  // ===== 폼 콘텐츠 렌더링 =====
  const renderFormContent = useCallback(() => (
    <>
      <div className="space-y-6">
        {/* 기본 정보 */}
        <Card>
          <CardHeader className="bg-muted/50">
            <CardTitle className="text-base">기본 정보</CardTitle>
          </CardHeader>
          <CardContent className="pt-6">
            {/* 반응형 6열 그리드: PC 6열, 태블릿 4열, 작은태블릿 2열, 모바일 1열 */}
            {/* 4개 필드 → 2+1+2+1 = 6열 채움 */}
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-6">
              <div className="space-y-2 lg:col-span-2">
                <Label htmlFor="processName">공정명 *</Label>
                <Input
                  id="processName"
                  value={processName}
                  onChange={(e) => setProcessName(e.target.value)}
                  placeholder="예: 스크린"
                />
              </div>
              <div className="space-y-2">
                <Label>공정구분</Label>
                <Select
                  value={processType}
                  onValueChange={(v) => setProcessType(v as ProcessType)}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {PROCESS_TYPE_OPTIONS.map((opt) => (
                      <SelectItem key={opt.value} value={opt.value}>
                        {opt.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2 lg:col-span-2">
                <Label>담당부서 *</Label>
                <Select value={department} onValueChange={setDepartment} disabled={isDepartmentsLoading}>
                  <SelectTrigger>
                    <SelectValue placeholder={isDepartmentsLoading ? "로딩 중..." : "선택하세요"} />
                  </SelectTrigger>
                  <SelectContent>
                    {departmentOptions.map((opt) => (
                      <SelectItem key={opt.id} value={opt.value}>
                        {opt.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>작업일지 양식</Label>
                <Select value={workLogTemplate} onValueChange={setWorkLogTemplate}>
                  <SelectTrigger>
                    <SelectValue placeholder="선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    {WORK_LOG_OPTIONS.map((opt) => (
                      <SelectItem key={opt.value} value={opt.value}>
                        {opt.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 자동 분류 규칙 */}
        <Card>
          <CardHeader className="bg-muted/50">
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="text-base">자동 분류 규칙</CardTitle>
                <p className="text-sm text-muted-foreground mt-1">
                  품목이 이 공정에 이동으로 분류되는 규칙을 생성합니다.
                </p>
              </div>
              <Button onClick={() => setRuleModalOpen(true)}>
                <Plus className="h-4 w-4 mr-2" />
                규칙 추가
              </Button>
            </div>
          </CardHeader>
          <CardContent className="pt-6">
            {classificationRules.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                <Wrench className="h-12 w-12 mx-auto mb-4 opacity-30" />
                <p className="font-medium">품목별 규칙이 없습니다</p>
                <p className="text-sm mt-1">
                  규칙을 추가하면 해당 패턴의 품목이 이 공정으로 분류됩니다
                </p>
              </div>
            ) : (
              <div className="space-y-3">
                {classificationRules.map((rule, index) => {
                  // 개별 품목인 경우 품목 개수 계산
                  const isIndividual = rule.registrationType === 'individual';
                  const itemCount = isIndividual
                    ? rule.conditionValue.split(',').filter(Boolean).length
                    : 0;

                  return (
                    <div
                      key={rule.id}
                      className="flex items-start justify-between p-4 border rounded-lg"
                    >
                      <div className="flex gap-3">
                        {/* 번호 */}
                        <span className="text-muted-foreground font-medium mt-0.5">
                          {index + 1}.
                        </span>
                        <div className="space-y-1">
                          {/* 제목 */}
                          <div className="font-medium">
                            {isIndividual ? (
                              <>개별 품목 지정 - {itemCount}개 품목</>
                            ) : (
                              <>
                                {rule.ruleType}{' '}
                                {
                                  MATCHING_TYPE_OPTIONS.find(
                                    (o) => o.value === rule.matchingType
                                  )?.label
                                }{' '}
                                "{rule.conditionValue}"
                              </>
                            )}
                          </div>
                          {/* 뱃지 + 우선순위 */}
                          <div className="flex items-center gap-2">
                            <Badge variant="secondary" className="text-xs">
                              {isIndividual
                                ? `${itemCount}개 품목 배정됨`
                                : rule.isActive
                                  ? '활성'
                                  : '비활성'}
                            </Badge>
                            <span className="text-sm text-muted-foreground">
                              우선순위: {rule.priority}
                            </span>
                          </div>
                          {/* 설명 */}
                          <div className="text-sm text-muted-foreground">
                            {isIndividual
                              ? `직접 선택한 품목 ${itemCount}개`
                              : rule.description || ''}
                          </div>
                        </div>
                      </div>
                      {/* 수정/삭제 버튼 */}
                      <div className="flex items-center gap-1">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleEditRule(rule)}
                          className="h-8 w-8"
                        >
                          <Pencil className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleDeleteRule(rule.id)}
                          className="h-8 w-8 text-muted-foreground hover:text-destructive"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </CardContent>
        </Card>

        {/* 작업 정보 */}
        <Card>
          <CardHeader className="bg-muted/50">
            <CardTitle className="text-base">작업 정보</CardTitle>
          </CardHeader>
          <CardContent className="pt-6">
            {/* 반응형 6열 그리드: PC 6열, 태블릿 4열, 작은태블릿 2열, 모바일 1열 */}
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-6">
              <div className="space-y-2">
                <Label>필요인원</Label>
                <QuantityInput
                  value={requiredWorkers}
                  onChange={(value) => setRequiredWorkers(value ?? 1)}
                  min={1}
                />
              </div>
              <div className="space-y-2 lg:col-span-2">
                <Label>설비정보</Label>
                <Input
                  value={equipmentInfo}
                  onChange={(e) => setEquipmentInfo(e.target.value)}
                  placeholder="예: 미싱기 3대, 절단기 1대"
                />
              </div>
              <div className="space-y-2 lg:col-span-3">
                <Label>세부 작업단계 (쉼표로 구분)</Label>
                <Input
                  value={workSteps}
                  onChange={(e) => setWorkSteps(e.target.value)}
                  placeholder="예: 원단절단, 미싱, 핸드작업, 중간검사, 포장"
                />
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 설명 */}
        <Card>
          <CardHeader className="bg-muted/50">
            <CardTitle className="text-base">설명</CardTitle>
          </CardHeader>
          <CardContent className="pt-6 space-y-6">
            <div className="space-y-2">
              <Label>설명</Label>
              <Textarea
                value={note}
                onChange={(e) => setNote(e.target.value)}
                placeholder="공정에 대한 설명"
                rows={4}
              />
            </div>
            <div className="flex items-center gap-2">
              <Checkbox
                id="isActive"
                checked={isActive}
                onCheckedChange={(checked) => setIsActive(checked as boolean)}
              />
              <Label htmlFor="isActive" className="font-normal">
                사용함
              </Label>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 규칙 추가/수정 모달 */}
      <RuleModal
        open={ruleModalOpen}
        onOpenChange={handleModalClose}
        onAdd={handleSaveRule}
        editRule={editingRule}
      />
    </>
  ), [
    processName, processType, department, workLogTemplate, classificationRules,
    requiredWorkers, equipmentInfo, workSteps, note, isActive, ruleModalOpen,
    editingRule, departmentOptions, isDepartmentsLoading, handleSaveRule,
    handleEditRule, handleDeleteRule, handleModalClose,
  ]);

  // Config 선택 (create/edit)
  const config = isEdit ? processEditConfig : processCreateConfig;

  return (
    <IntegratedDetailTemplate
      config={config}
      mode={isEdit ? 'edit' : 'create'}
      isLoading={isDepartmentsLoading}
      isSubmitting={isLoading}
      onBack={handleCancel}
      onCancel={handleCancel}
      onSubmit={handleSubmit}
      renderForm={renderFormContent}
    />
  );
}
