'use client';

/**
 * 재고생산 상세 보기 컴포넌트
 *
 * - BendingLotForm(등록/수정)과 동일한 레이아웃 (읽기 전용)
 * - 기본 정보, 품목 선택, LOT 정보, 메모 섹션
 */

import { useState, useEffect, useMemo } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import {
  Package,
  ClipboardList,
  MessageSquare,
  Tag,
  Layers,
  Copy,
} from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { FormSection } from '@/components/organisms/FormSection';
import {
  getStockOrderById,
  getBendingCodeMap,
  deleteStockOrder,
  type StockOrder,
  type BendingCodeMap,
} from './actions';
import type { DetailConfig } from '@/components/templates/IntegratedDetailTemplate/types';

// ============================================================================
// Config
// ============================================================================

const stockDetailConfig: DetailConfig = {
  title: '절곡품 재고생산',
  description: '재고생산 정보를 조회합니다',
  icon: Package,
  basePath: '/sales/stocks',
  fields: [],
  actions: {
    showBack: true,
    showEdit: true,
    showDelete: true,
    backLabel: '목록',
  },
};

// ============================================================================
// Props
// ============================================================================

interface StockProductionDetailProps {
  orderId: string;
}

// ============================================================================
// Component
// ============================================================================

export function StockProductionDetail({ orderId }: StockProductionDetailProps) {
  const router = useRouter();
  const params = useParams();
  const locale = (params.locale as string) || 'ko';
  const basePath = `/${locale}/sales/stocks`;

  const [order, setOrder] = useState<StockOrder | null>(null);
  const [codeMap, setCodeMap] = useState<BendingCodeMap | null>(null);
  const [loading, setLoading] = useState(true);

  // 데이터 로드
  useEffect(() => {
    async function load() {
      try {
        setLoading(true);
        const [orderResult, codeMapResult] = await Promise.all([
          getStockOrderById(orderId),
          getBendingCodeMap(),
        ]);

        if (orderResult.__authError) {
          toast.error('인증이 만료되었습니다.');
          return;
        }
        if (orderResult.success && orderResult.data) {
          setOrder(orderResult.data);
        } else {
          toast.error(orderResult.error || '재고생산 정보를 불러오는데 실패했습니다.');
        }

        if (codeMapResult.success && codeMapResult.data) {
          setCodeMap(codeMapResult.data);
        }
      } finally {
        setLoading(false);
      }
    }
    load();
  }, [orderId]);

  // 코드 → 이름 변환
  const prodName = useMemo(() => {
    if (!codeMap || !order?.bendingLot?.prodCode) return order?.bendingLot?.prodCode || '-';
    return codeMap.products.find((p) => p.code === order.bendingLot!.prodCode)?.name || order.bendingLot.prodCode;
  }, [codeMap, order]);

  const specName = useMemo(() => {
    if (!codeMap || !order?.bendingLot?.specCode) return order?.bendingLot?.specCode || '-';
    return codeMap.specs.find((s) => s.code === order.bendingLot!.specCode)?.name || order.bendingLot.specCode;
  }, [codeMap, order]);

  const lengthName = useMemo(() => {
    if (!codeMap || !order?.bendingLot?.prodCode || !order?.bendingLot?.lengthCode) return order?.bendingLot?.lengthCode || '-';
    const lengths = order.bendingLot.prodCode === 'G'
      ? codeMap.lengths.smoke_barrier
      : codeMap.lengths.general;
    return lengths.find((l) => l.code === order.bendingLot!.lengthCode)?.name || order.bendingLot.lengthCode;
  }, [codeMap, order]);

  // 연기차단재 여부
  const isSmokeBarrier = order?.bendingLot?.prodCode === 'G';


  // 품목 정보 (첫 번째 아이템)
  const item = order?.items?.[0];

  // renderView — 등록 화면(BendingLotForm)과 동일한 레이아웃
  const renderViewContent = useMemo(
    () =>
      (data: StockOrder) => (
        <div className="space-y-6">
          {/* 기본 정보 */}
          <FormSection title="기본 정보" icon={ClipboardList}>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="space-y-2">
                <Label>생산번호</Label>
                <Input value={data.orderNo} disabled />
              </div>
              <div className="space-y-2">
                <Label>품목코드</Label>
                <Input value={data.items?.[0]?.itemCode || '-'} disabled />
              </div>
              <div className="space-y-2">
                <Label>로트번호</Label>
                <Input value={data.bendingLot?.lotNumber || '-'} disabled />
              </div>
              <div className="space-y-2">
                <Label>등록일</Label>
                <Input value={data.regDate} disabled />
              </div>
              <div className="space-y-2">
                <Label>수량</Label>
                <Input value={String(data.targetStockQty || data.quantity || '-')} disabled />
              </div>
              <div className="space-y-2">
                <Label>진행상태</Label>
                {(() => {
                  const statusConfig: Record<string, { label: string; className: string }> = {
                    draft: { label: '등록', className: 'bg-gray-100 text-gray-700' },
                    confirmed: { label: '확정', className: 'bg-blue-100 text-blue-700' },
                    in_progress: { label: '생산지시완료', className: 'bg-indigo-100 text-indigo-700' },
                    in_production: { label: '생산중', className: 'bg-green-100 text-green-700' },
                    produced: { label: '생산완료', className: 'bg-teal-100 text-teal-700' },
                    completed: { label: '생산완료', className: 'bg-teal-100 text-teal-700' },
                    cancelled: { label: '취소', className: 'bg-red-100 text-red-700' },
                  };
                  const s = statusConfig[data.status] || { label: data.status || '-', className: 'bg-gray-100 text-gray-600' };
                  return (
                    <div className={`inline-flex items-center px-3 py-2 rounded-md text-sm font-medium ${s.className}`}>
                      {s.label}
                    </div>
                  );
                })()}
              </div>
            </div>
          </FormSection>

          {/* 품목 선택 (캐스케이딩 — 읽기 전용) */}
          {data.bendingLot && (
            <FormSection title="품목 선택" icon={Layers}>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="space-y-2">
                  <Label>품목명</Label>
                  <Input value={prodName} disabled />
                </div>
                <div className="space-y-2">
                  <Label>종류</Label>
                  <Input value={specName} disabled />
                </div>
                <div className="space-y-2">
                  <Label>모양&길이</Label>
                  <Input value={lengthName} disabled />
                </div>
              </div>

              {/* 매핑된 품목 표시 */}
              {item && item.itemCode && (
                <div className="mt-4 p-3 bg-green-50 border border-green-200 rounded-md">
                  <p className="text-sm font-medium text-green-800">매핑된 품목</p>
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-2 mt-2 text-sm">
                    <div>
                      <span className="text-muted-foreground">품목코드: </span>
                      <code className="bg-green-100 px-1 rounded">{item.itemCode}</code>
                    </div>
                    <div>
                      <span className="text-muted-foreground">품목명: </span>
                      {item.itemName}
                    </div>
                    <div>
                      <span className="text-muted-foreground">규격: </span>
                      {item.specification || '-'}
                    </div>
                    <div>
                      <span className="text-muted-foreground">단위: </span>
                      {item.unit}
                    </div>
                  </div>
                </div>
              )}
            </FormSection>
          )}

          {/* LOT 정보 */}
          {data.bendingLot && (
            <FormSection title="LOT 정보" icon={Tag}>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>생산품 LOT</Label>
                  <Input value={data.bendingLot.lotNumber || '-'} disabled />
                </div>
                <div className="space-y-2">
                  <Label>원자재 재질</Label>
                  <Input value={data.bendingLot.material || '-'} disabled />
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
                <div className="space-y-2">
                  <Label>원자재(철판) LOT</Label>
                  <Input value={data.bendingLot.rawLotNo || '-'} disabled />
                </div>
                {isSmokeBarrier && (
                  <div className="space-y-2">
                    <Label>원단 LOT</Label>
                    <Input value={data.bendingLot.fabricLotNo || '-'} disabled />
                  </div>
                )}
              </div>
            </FormSection>
          )}

          {/* 메모 */}
          <FormSection title="메모" icon={MessageSquare}>
            <div className="space-y-2">
              <Label>메모</Label>
              <Textarea
                value={data.memo || ''}
                disabled
                placeholder="메모 없음"
                rows={3}
              />
            </div>
          </FormSection>
        </div>
      ),
    [prodName, specName, lengthName, isSmokeBarrier, item]
  );

  return (
    <>
      <IntegratedDetailTemplate
        config={stockDetailConfig}
        mode="view"
        initialData={order as unknown as Record<string, unknown>}
        itemId={orderId}
        isLoading={loading}
        onCancel={() => router.push(basePath)}
        onDelete={async (id) => {
          const result = await deleteStockOrder(String(id));
          if (result.__authError) {
            return { success: false, error: '인증이 만료되었습니다.' };
          }
          return { success: result.success, error: result.error };
        }}
        headerActions={
          <Button
            variant="outline"
            size="sm"
            onClick={() => router.push(`${basePath}?mode=new&copyFrom=${orderId}`)}
          >
            <Copy className="h-4 w-4 mr-1" />
            복사
          </Button>
        }
        renderView={(data) => renderViewContent(data as unknown as StockOrder)}
      />
    </>
  );
}
