'use client';

/**
 * 품목관리 상세 페이지
 * IntegratedDetailTemplate 마이그레이션 완료 (2026-01-20)
 */

import { useState, useEffect, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { itemConfig } from './itemConfig';
import { toast } from 'sonner';
import type { ItemFormData, ItemType, OrderType, ItemStatus, OrderItem } from './types';
import {
  ITEM_TYPE_OPTIONS,
  ORDER_TYPE_OPTIONS,
  STATUS_OPTIONS,
  UNIT_OPTIONS,
} from './constants';
import { getItem, createItem, updateItem, deleteItem, getCategoryOptions } from './actions';
import { BomTreeViewer } from '@/components/items/BomTreeViewer';

interface ItemDetailClientProps {
  itemId?: string;
  isEditMode?: boolean;
  isNewMode?: boolean;
}

const initialFormData: ItemFormData = {
  itemNumber: '',
  itemType: '제품',
  categoryId: '',
  itemName: '', specification: '',
  unit: 'SET',
  orderType: '경품발주',
  status: '사용',
  note: '',
  orderItems: [],
};

export default function ItemDetailClient({
  itemId,
  isEditMode = false,
  isNewMode = false,
}: ItemDetailClientProps) {
  const router = useRouter();

  // 모드 계산 (IntegratedDetailTemplate은 'create'를 기대)
  const mode = isNewMode ? 'create' : isEditMode ? 'edit' : 'view';
  const isViewMode = mode === 'view';

  // 폼 데이터
  const [formData, setFormData] = useState<ItemFormData>(initialFormData);

  // 카테고리 옵션
  const [categoryOptions, setCategoryOptions] = useState<{ id: string; name: string }[]>([]);

  // 상태
  const [isLoading, setIsLoading] = useState(false);
  const [isSaving, setIsSaving] = useState(false);

  // 카테고리 목록 로드
  useEffect(() => {
    const loadCategories = async () => {
      const result = await getCategoryOptions();
      if (result.success && result.data) {
        setCategoryOptions(result.data);
      }
    };
    loadCategories();
  }, []);

  // 품목 데이터 로드
  useEffect(() => {
    if (itemId && !isNewMode) {
      const loadItem = async () => {
        setIsLoading(true);
        try {
          const result = await getItem(itemId);
          if (result.success && result.data) {
            setFormData({
              itemNumber: result.data.itemNumber,
              itemType: result.data.itemType,
              categoryId: result.data.categoryId,
              itemName: result.data.itemName,
              specification: result.data.specification,
              unit: result.data.unit,
              orderType: result.data.orderType,
              status: result.data.status,
              note: result.data.note || '',
              orderItems: result.data.orderItems || [],
            });
          } else {
            toast.error(result.error || '품목 정보를 불러오는데 실패했습니다.');
            router.push('/ko/construction/order/base-info/items');
          }
        } catch {
          toast.error('품목 정보를 불러오는데 실패했습니다.');
          router.push('/ko/construction/order/base-info/items');
        } finally {
          setIsLoading(false);
        }
      };
      loadItem();
    }
  }, [itemId, isNewMode, router]);

  // 폼 필드 변경
  const handleFieldChange = useCallback(
    (field: keyof ItemFormData, value: string | OrderItem[]) => {
      setFormData((prev) => ({ ...prev, [field]: value }));
    },
    []
  );

  // 발주 항목 추가
  const handleAddOrderItem = useCallback(() => {
    const newItem: OrderItem = {
      id: `new-${Date.now()}`,
      label: '',
      value: '',
    };
    setFormData((prev) => ({
      ...prev,
      orderItems: [...prev.orderItems, newItem],
    }));
  }, []);

  // 발주 항목 삭제
  const handleRemoveOrderItem = useCallback((id: string) => {
    setFormData((prev) => ({
      ...prev,
      orderItems: prev.orderItems.filter((item) => item.id !== id),
    }));
  }, []);

  // 발주 항목 변경
  const handleOrderItemChange = useCallback(
    (id: string, field: 'label' | 'value', value: string) => {
      setFormData((prev) => ({
        ...prev,
        orderItems: prev.orderItems.map((item) =>
          item.id === id ? { ...item, [field]: value } : item
        ),
      }));
    },
    []
  );

  // 동적 config (mode에 따라 title 변경)
  // Note: IntegratedDetailTemplate 제목 로직:
  // - create 모드: ${config.title} 등록
  // - view 모드: config.title (접미사 없음)
  // - edit 모드: ${config.title} 수정
  const dynamicConfig = useMemo(() => {
    return {
      ...itemConfig,
      title: isViewMode ? '품목 상세' : '품목',
    };
  }, [isViewMode]);

  // onSubmit 핸들러 (Promise 반환)
  const handleFormSubmit = useCallback(async () => {
    // 유효성 검사
    if (!formData.itemNumber.trim()) {
      toast.error('품목번호를 입력해주세요.');
      return { success: false, error: '품목번호를 입력해주세요.' };
    }
    if (!formData.itemName.trim()) {
      toast.error('품목명을 입력해주세요.');
      return { success: false, error: '품목명을 입력해주세요.' };
    }

    setIsSaving(true);
    try {
      if (mode === 'create') {
        const result = await createItem(formData);
        if (result.success && result.data) {
          toast.success('품목이 등록되었습니다.');
          router.push(`/ko/construction/order/base-info/items/${result.data.id}?mode=view`);
          return { success: true };
        } else {
          toast.error(result.error || '품목 등록에 실패했습니다.');
          return { success: false, error: result.error || '품목 등록에 실패했습니다.' };
        }
      } else if (mode === 'edit' && itemId) {
        const result = await updateItem(itemId, formData);
        if (result.success) {
          toast.success('품목이 수정되었습니다.');
          router.push(`/ko/construction/order/base-info/items/${itemId}?mode=view`);
          return { success: true };
        } else {
          toast.error(result.error || '품목 수정에 실패했습니다.');
          return { success: false, error: result.error || '품목 수정에 실패했습니다.' };
        }
      }
      return { success: false, error: '알 수 없는 오류' };
    } catch {
      toast.error('저장 중 오류가 발생했습니다.');
      return { success: false, error: '저장 중 오류가 발생했습니다.' };
    } finally {
      setIsSaving(false);
    }
  }, [mode, formData, itemId, router]);

  // onDelete 핸들러 (Promise 반환)
  const handleFormDelete = useCallback(async () => {
    if (!itemId) return { success: false, error: '삭제할 품목이 없습니다.' };

    setIsLoading(true);
    try {
      const result = await deleteItem(itemId);
      if (result.success) {
        toast.success('품목이 삭제되었습니다.');
        router.push('/ko/construction/order/base-info/items');
        return { success: true };
      } else {
        toast.error(result.error || '품목 삭제에 실패했습니다.');
        return { success: false, error: result.error || '품목 삭제에 실패했습니다.' };
      }
    } catch {
      toast.error('삭제 중 오류가 발생했습니다.');
      return { success: false, error: '삭제 중 오류가 발생했습니다.' };
    } finally {
      setIsLoading(false);
    }
  }, [itemId, router]);

  // 폼 콘텐츠 렌더링
  const renderFormContent = useCallback(() => (
    <div className="space-y-6">
          {/* 기본 정보 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-base">기본 정보</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* Row 1: 품목번호, 품목유형 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="itemNumber">
                    품목번호 <span className="text-destructive">*</span>
                  </Label>
                  <Input
                    id="itemNumber"
                    value={formData.itemNumber}
                    onChange={(e) => handleFieldChange('itemNumber', e.target.value)}
                    placeholder="품목번호를 입력하세요"
                    disabled={isViewMode}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="itemType">
                    품목유형 <span className="text-destructive">*</span>
                  </Label>
                  <Select
                    value={formData.itemType}
                    onValueChange={(v) => handleFieldChange('itemType', v as ItemType)}
                    disabled={isViewMode}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="품목유형 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {ITEM_TYPE_OPTIONS.filter((o) => o.value !== 'all').map((option) => (
                        <SelectItem key={option.value} value={option.value}>
                          {option.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {/* Row 2: 카테고리명 */}
              <div className="space-y-2">
                <Label htmlFor="categoryId">카테고리명</Label>
                <Select
                  value={formData.categoryId}
                  onValueChange={(v) => handleFieldChange('categoryId', v)}
                  disabled={isViewMode}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="카테고리 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {categoryOptions.map((category) => (
                      <SelectItem key={category.id} value={category.id}>
                        {category.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* Row 3: 품목명, 규격 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="itemName">
                    품목명 <span className="text-destructive">*</span>
                  </Label>
                  <Input
                    id="itemName"
                    value={formData.itemName}
                    onChange={(e) => handleFieldChange('itemName', e.target.value)}
                    placeholder="품목명을 입력하세요"
                    disabled={isViewMode}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="specification">규격</Label>
                  <Input
                    id="specification"
                    value={formData.specification}
                    onChange={(e) => handleFieldChange('specification', e.target.value)}
                    placeholder="규격을 입력하세요 (예: 1∅220V)"
                    disabled={isViewMode}
                  />
                </div>
              </div>

              {/* Row 4: 단위, 구분 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="unit">단위</Label>
                  <Select
                    value={formData.unit}
                    onValueChange={(v) => handleFieldChange('unit', v)}
                    disabled={isViewMode}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="단위 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {UNIT_OPTIONS.map((unit) => (
                        <SelectItem key={unit} value={unit}>
                          {unit}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="orderType">구분</Label>
                  <Select
                    value={formData.orderType}
                    onValueChange={(v) => handleFieldChange('orderType', v as OrderType)}
                    disabled={isViewMode}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="구분 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {ORDER_TYPE_OPTIONS.filter((o) => o.value !== 'all').map((option) => (
                        <SelectItem key={option.value} value={option.value}>
                          {option.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {/* Row 5: 상태, 비고 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="status">상태</Label>
                  <Select
                    value={formData.status}
                    onValueChange={(v) => handleFieldChange('status', v as ItemStatus)}
                    disabled={isViewMode}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="상태 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {STATUS_OPTIONS.filter((o) => o.value !== 'all').map((option) => (
                        <SelectItem key={option.value} value={option.value}>
                          {option.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="note">비고</Label>
                  <Input
                    id="note"
                    value={formData.note || ''}
                    onChange={(e) => handleFieldChange('note', e.target.value)}
                    placeholder="비고를 입력하세요"
                    disabled={isViewMode}
                  />
                </div>
              </div>

              {/* 발주 항목 구분정보 */}
              {/* 수정 모드: 항상 표시 (추가/삭제 가능) */}
              {/* 상세 모드: 데이터가 있을 때만 표시 (읽기 전용) */}
              {(!isViewMode || formData.orderItems.length > 0) && (
                <div className="pt-4">
                  {/* 헤더 */}
                  <div className="grid grid-cols-[1fr_1fr_auto] gap-4 items-center mb-4">
                    <div className="text-base font-semibold">발주 항목</div>
                    <div className="text-base font-semibold">구분 정보</div>
                    {!isViewMode && (
                      <Button size="sm" onClick={handleAddOrderItem}>
                        추가
                      </Button>
                    )}
                  </div>

                  {/* 항목 리스트 */}
                  {formData.orderItems.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground border rounded-lg">
                      발주 항목이 없습니다. 추가 버튼을 클릭하여 항목을 추가하세요.
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {formData.orderItems.map((item) => (
                        <div key={item.id} className={`grid ${isViewMode ? 'grid-cols-2' : 'grid-cols-[1fr_1fr_auto]'} gap-4 items-center`}>
                          <Input
                            value={item.label}
                            onChange={(e) => handleOrderItemChange(item.id, 'label', e.target.value)}
                            placeholder="예: 무게"
                            disabled={isViewMode}
                          />
                          <Input
                            value={item.value}
                            onChange={(e) => handleOrderItemChange(item.id, 'value', e.target.value)}
                            placeholder="예: 400KG"
                            disabled={isViewMode}
                          />
                          {!isViewMode && (
                            <Button
                              variant="default"
                              size="icon"
                              className="h-10 w-10 bg-black hover:bg-black/80"
                              onClick={() => handleRemoveOrderItem(item.id)}
                            >
                              <Trash2 className="h-4 w-4 text-white" />
                            </Button>
                          )}
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </CardContent>
          </Card>

          {/* BOM 트리 */}
          {itemId && <BomTreeViewer itemId={itemId} itemType={formData.itemType} />}
    </div>
  ), [
    formData,
    isViewMode,
    categoryOptions,
    handleFieldChange,
    handleAddOrderItem,
    handleRemoveOrderItem,
    handleOrderItemChange,
    itemId,
  ]);

  return (
    <IntegratedDetailTemplate
      config={dynamicConfig}
      mode={mode}
      initialData={formData as unknown as Record<string, unknown>}
      itemId={itemId}
      isLoading={isLoading || isSaving}
      onSubmit={handleFormSubmit}
      onDelete={handleFormDelete}
      renderView={() => renderFormContent()}
      renderForm={() => renderFormContent()}
    />
  );
}