'use client';

/**
 * 부적합관리 - 등록/수정 폼
 *
 * IntegratedDetailTemplate + 5개 FormSection
 * 1. 기본 정보
 * 2. 불량 내역
 * 3. 원인 분석 및 처리 방안
 * 4. 자재 내역 및 비용
 * 5. 비고
 */

import { useState, useEffect, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
  FileWarning,
  Info,
  AlertCircle,
  Wrench,
  Package,
  MessageSquare,
} from 'lucide-react';
import { Input } from '@/components/ui/input';
import { DatePicker } from '@/components/ui/date-picker';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { NumberInput } from '@/components/ui/number-input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { toast } from 'sonner';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { FormSection } from '@/components/organisms/FormSection';
import { formatAmount } from '@/lib/utils/amount';
import {
  createNonconformingReport,
  updateNonconformingReport,
  getNonconformingReport,
} from './actions';
import { NonconformingItemTable } from './NonconformingItemTable';
import {
  NC_TYPE_OPTIONS,
  NC_STATUS_CONFIG,
  INITIAL_FORM_DATA,
  type NonconformingFormData,
  type NonconformingDetail,
  type NcType,
  type NcStatus,
} from './types';
import type { DetailConfig } from '@/components/templates/IntegratedDetailTemplate/types';
import { BadgeSm } from '@/components/atoms/BadgeSm';

const BASE_PATH = '/material/nonconforming-management';

const formCreateConfig: DetailConfig = {
  title: '부적합',
  description: '부적합 보고서를 등록합니다',
  icon: FileWarning,
  basePath: BASE_PATH,
  fields: [],
  actions: {
    showBack: true,
    showSave: true,
    submitLabel: '저장',
    backLabel: '취소',
  },
};

const formEditConfig: DetailConfig = {
  title: '부적합',
  description: '부적합 보고서를 수정합니다',
  icon: FileWarning,
  basePath: BASE_PATH,
  fields: [],
  actions: {
    showBack: true,
    showSave: true,
    submitLabel: '저장',
    backLabel: '취소',
  },
};

interface NonconformingFormProps {
  id?: string;
  mode: 'new' | 'edit';
}

export function NonconformingForm({ id, mode }: NonconformingFormProps) {
  const router = useRouter();
  const isNew = mode === 'new';
  const [form, setForm] = useState<NonconformingFormData>({ ...INITIAL_FORM_DATA });
  const [isLoading, setIsLoading] = useState(!isNew);
  const [isSaving, setIsSaving] = useState(false);
  const [detailData, setDetailData] = useState<NonconformingDetail | null>(null);

  const config = isNew ? formCreateConfig : formEditConfig;

  // 데이터 로드 (수정 모드)
  useEffect(() => {
    if (isNew || !id) { setIsLoading(false); return; }
    getNonconformingReport(id).then((result) => {
      if (result.success && result.data) {
        const d = result.data as NonconformingDetail;
        setDetailData(d);
        setForm({
          nc_type: d.nc_type,
          occurred_at: d.occurred_at || '',
          confirmed_at: d.confirmed_at || '',
          site_name: d.site_name || '',
          department_id: d.department?.id ?? null,
          order_id: d.order?.id ?? null,
          item_id: d.item?.id ?? null,
          defect_quantity: d.defect_quantity ?? '',
          unit: d.unit || 'EA',
          defect_description: d.defect_description || '',
          cause_analysis: d.cause_analysis || '',
          corrective_action: d.corrective_action || '',
          action_manager_id: d.action_manager?.id ?? null,
          related_employee_id: d.related_employee?.id ?? null,
          shipping_cost: d.shipping_cost || 0,
          construction_cost: d.construction_cost || 0,
          other_cost: d.other_cost || 0,
          drawing_location: d.drawing_location || '',
          remarks: d.remarks || '',
          items: d.items || [],
        });
      } else {
        toast.error(result.error || '데이터 조회 실패');
        router.push(BASE_PATH);
      }
      setIsLoading(false);
    });
  }, [id, isNew, router]);

  // 자재비용 합계 계산
  const materialCost = useMemo(
    () => form.items.reduce((sum, item) => sum + (item.amount || 0), 0),
    [form.items]
  );

  // 총 비용 합계
  const totalCost = useMemo(
    () => materialCost + Number(form.shipping_cost || 0) + Number(form.construction_cost || 0) + Number(form.other_cost || 0),
    [materialCost, form.shipping_cost, form.construction_cost, form.other_cost]
  );

  // 필드 변경
  const handleChange = useCallback(
    <K extends keyof NonconformingFormData>(key: K, value: NonconformingFormData[K]) => {
      setForm((prev) => ({ ...prev, [key]: value }));
    },
    []
  );

  // 저장 (IntegratedDetailTemplate의 onSubmit 시그니처에 맞춤)
  const handleSubmit = useCallback(async (_data: Record<string, unknown>) => {
    // 필수 체크
    if (!form.nc_type) { toast.error('부적합 유형을 선택하세요.'); return { success: false, error: '' }; }
    if (!form.occurred_at) { toast.error('발생일을 입력하세요.'); return { success: false, error: '' }; }

    const payload: Record<string, unknown> = {
      nc_type: form.nc_type,
      occurred_at: form.occurred_at,
      confirmed_at: form.confirmed_at || undefined,
      site_name: form.site_name || undefined,
      department_id: form.department_id || undefined,
      order_id: form.order_id || undefined,
      item_id: form.item_id || undefined,
      defect_quantity: form.defect_quantity ? Number(form.defect_quantity) : undefined,
      unit: form.unit || undefined,
      defect_description: form.defect_description || undefined,
      cause_analysis: form.cause_analysis || undefined,
      corrective_action: form.corrective_action || undefined,
      action_manager_id: form.action_manager_id || undefined,
      related_employee_id: form.related_employee_id || undefined,
      shipping_cost: Number(form.shipping_cost || 0),
      construction_cost: Number(form.construction_cost || 0),
      other_cost: Number(form.other_cost || 0),
      drawing_location: form.drawing_location || undefined,
      remarks: form.remarks || undefined,
      items: form.items.map((item) => ({
        item_id: item.item_id || undefined,
        item_name: item.item_name,
        specification: item.specification,
        quantity: Number(item.quantity || 0),
        unit_price: Number(item.unit_price || 0),
        remarks: item.remarks || undefined,
      })),
    };
    // undefined 값 제거
    Object.keys(payload).forEach(key => {
      if (payload[key] === undefined) delete payload[key];
    });

    const result = isNew
      ? await createNonconformingReport(payload)
      : await updateNonconformingReport(id!, payload);

    return { success: result.success, error: result.error || '' };
  }, [form, isNew, id]);

  const handleBack = useCallback(() => {
    router.push(BASE_PATH);
  }, [router]);

  return (
    <IntegratedDetailTemplate
      config={config}
      mode={isNew ? 'create' : 'edit'}
      isLoading={isLoading}
      onSubmit={handleSubmit}
      onCancel={handleBack}
      stickyButtons
      renderForm={() => (
        <div className="space-y-6">
          {/* 섹션 1: 기본 정보 */}
          <FormSection title="기본 정보" icon={Info}>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              {/* 부적합번호 (수정 시 읽기전용) */}
              {!isNew && detailData && (
                <div className="space-y-2">
                  <Label>부적합번호</Label>
                  <Input value={detailData.nc_number} disabled />
                </div>
              )}

              {/* 상태 (수정 시 표시) */}
              {!isNew && detailData && (
                <div className="space-y-2">
                  <Label>상태</Label>
                  <div className="flex items-center h-9">
                    <BadgeSm className={NC_STATUS_CONFIG[detailData.status].className}>
                      {NC_STATUS_CONFIG[detailData.status].label}
                    </BadgeSm>
                  </div>
                </div>
              )}

              {/* 발생일 */}
              <div className="space-y-2">
                <Label>발생일 <span className="text-red-500">*</span></Label>
                <DatePicker
                  value={form.occurred_at}
                  onChange={(date) => handleChange('occurred_at', date)}
                />
              </div>

              {/* 확인일 */}
              <div className="space-y-2">
                <Label>불량확인일</Label>
                <DatePicker
                  value={form.confirmed_at}
                  onChange={(date) => handleChange('confirmed_at', date)}
                />
              </div>

              {/* 부적합 유형 */}
              <div className="space-y-2">
                <Label>부적합 유형 <span className="text-red-500">*</span></Label>
                <Select
                  key={`nc_type-${form.nc_type}`}
                  value={form.nc_type}
                  onValueChange={(v) => handleChange('nc_type', v as NcType)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="유형 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {NC_TYPE_OPTIONS.map((o) => (
                      <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* 현장명 */}
              <div className="space-y-2">
                <Label>현장명</Label>
                <Input
                  value={form.site_name}
                  onChange={(e) => handleChange('site_name', e.target.value)}
                  placeholder="현장명"
                />
              </div>

              {/* 단위 */}
              <div className="space-y-2">
                <Label>단위</Label>
                <Input
                  value={form.unit}
                  onChange={(e) => handleChange('unit', e.target.value)}
                  placeholder="EA"
                />
              </div>
            </div>
          </FormSection>

          {/* 섹션 2: 불량 내역 */}
          <FormSection title="불량 내역" icon={AlertCircle} variant="highlighted">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              {/* 불량 수량 */}
              <div className="space-y-2">
                <Label>불량 수량</Label>
                <NumberInput
                  value={form.defect_quantity}
                  onChange={(val) => handleChange('defect_quantity', val ?? '')}
                  allowDecimal
                  min={0}
                  placeholder="수량"
                />
              </div>
            </div>
            <div className="mt-4 space-y-2">
              <Label>불량 상세 설명</Label>
              <Textarea
                value={form.defect_description}
                onChange={(e) => handleChange('defect_description', e.target.value)}
                placeholder="불량 상세 설명을 입력하세요"
                rows={4}
              />
            </div>
          </FormSection>

          {/* 섹션 3: 원인 분석 및 처리 방안 */}
          <FormSection title="원인 분석 및 처리 방안" icon={Wrench} variant="highlighted">
            <div className="space-y-4">
              <div className="space-y-2">
                <Label>불량 발생 원인 및 분석</Label>
                <Textarea
                  value={form.cause_analysis}
                  onChange={(e) => handleChange('cause_analysis', e.target.value)}
                  placeholder="원인 분석 내용을 입력하세요"
                  rows={4}
                />
              </div>
              <div className="space-y-2">
                <Label>처리 방안 및 개선 사항</Label>
                <Textarea
                  value={form.corrective_action}
                  onChange={(e) => handleChange('corrective_action', e.target.value)}
                  placeholder="처리 방안 내용을 입력하세요"
                  rows={4}
                />
              </div>
            </div>
          </FormSection>

          {/* 섹션 4: 자재 내역 및 비용 */}
          <FormSection title="자재 내역 및 비용" icon={Package} variant="highlighted">
            {/* 자재 상세 테이블 */}
            <NonconformingItemTable
              items={form.items}
              onChange={(items) => handleChange('items', items)}
            />

            {/* 비용 요약 */}
            <div className="mt-6 border rounded-md p-4 bg-muted/30">
              <h4 className="text-sm font-semibold mb-3">비용 요약</h4>
              <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                <div className="space-y-1">
                  <Label className="text-xs text-muted-foreground">자재 비용</Label>
                  <div className="h-9 flex items-center px-3 bg-muted rounded-md text-sm font-medium">
                    {formatAmount(materialCost)}
                  </div>
                </div>
                <div className="space-y-1">
                  <Label className="text-xs text-muted-foreground">운송 비용</Label>
                  <NumberInput
                    value={form.shipping_cost}
                    onChange={(val) => handleChange('shipping_cost', val ?? 0)}
                    min={0}
                    useComma
                    className="h-9"
                  />
                </div>
                <div className="space-y-1">
                  <Label className="text-xs text-muted-foreground">시공 비용</Label>
                  <NumberInput
                    value={form.construction_cost}
                    onChange={(val) => handleChange('construction_cost', val ?? 0)}
                    min={0}
                    useComma
                    className="h-9"
                  />
                </div>
                <div className="space-y-1">
                  <Label className="text-xs text-muted-foreground">기타 비용</Label>
                  <NumberInput
                    value={form.other_cost}
                    onChange={(val) => handleChange('other_cost', val ?? 0)}
                    min={0}
                    useComma
                    className="h-9"
                  />
                </div>
                <div className="space-y-1">
                  <Label className="text-xs text-muted-foreground font-bold">비용 합계</Label>
                  <div className="h-9 flex items-center px-3 bg-blue-50 border border-blue-200 rounded-md text-sm font-bold text-blue-700">
                    {formatAmount(totalCost)}
                  </div>
                </div>
              </div>
            </div>
          </FormSection>

          {/* 섹션 5: 비고 */}
          <FormSection title="비고" icon={MessageSquare}>
            <div className="space-y-4">
              <div className="space-y-2">
                <Label>비고</Label>
                <Textarea
                  value={form.remarks}
                  onChange={(e) => handleChange('remarks', e.target.value)}
                  placeholder="비고 사항을 입력하세요"
                  rows={3}
                />
              </div>
              <div className="space-y-2">
                <Label>도면 저장 위치</Label>
                <Input
                  value={form.drawing_location}
                  onChange={(e) => handleChange('drawing_location', e.target.value)}
                  placeholder="예: nas2dual/도면/2026/03"
                />
              </div>
            </div>
          </FormSection>
        </div>
      )}
    />
  );
}
