'use client';

/**
 * 입고 상세 페이지
 * 상태에 따라 다른 UI 표시:
 * - 검사대기: 입고증, 목록, 검사등록 버튼
 * - 배송중/발주완료: 목록, 입고처리 버튼 (입고증 없음)
 * - 입고대기: 목록 버튼만 (입고증 없음)
 * - 입고완료: 입고증, 목록 버튼
 */

import { useState, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { Package, FileText, List, ClipboardCheck, Download } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { PageLayout } from '@/components/organisms/PageLayout';
import { mockReceivingItems, mockReceivingDetails } from './mockData';
import { RECEIVING_STATUS_LABELS, RECEIVING_STATUS_STYLES } from './types';
import type { ReceivingDetail as ReceivingDetailType } from './types';
import { ReceivingProcessDialog } from './ReceivingProcessDialog';
import { ReceivingReceiptDialog } from './ReceivingReceiptDialog';
import { SuccessDialog } from './SuccessDialog';

interface Props {
  id: string;
}

export function ReceivingDetail({ id }: Props) {
  const router = useRouter();
  const [isReceivingProcessDialogOpen, setIsReceivingProcessDialogOpen] = useState(false);
  const [isReceiptDialogOpen, setIsReceiptDialogOpen] = useState(false);
  const [successDialog, setSuccessDialog] = useState<{
    open: boolean;
    type: 'inspection' | 'receiving';
    lotNo?: string;
  }>({ open: false, type: 'receiving' });

  // 데이터 가져오기
  const detail: ReceivingDetailType | undefined = useMemo(() => {
    // 먼저 상세 데이터에서 찾기
    if (mockReceivingDetails[id]) {
      return mockReceivingDetails[id];
    }
    // 없으면 목록에서 변환
    const item = mockReceivingItems.find((i) => i.id === id);
    if (item) {
      return {
        id: item.id,
        orderNo: item.orderNo,
        orderDate: undefined,
        supplier: item.supplier,
        itemCode: item.itemCode,
        itemName: item.itemName,
        specification: undefined,
        orderQty: item.orderQty,
        orderUnit: item.orderUnit,
        dueDate: undefined,
        status: item.status,
        receivingDate: undefined,
        receivingQty: item.receivingQty,
        receivingLot: item.lotNo,
        supplierLot: undefined,
        receivingLocation: undefined,
        receivingManager: undefined,
      };
    }
    return undefined;
  }, [id]);

  // 목록으로 돌아가기
  const handleGoBack = useCallback(() => {
    router.push('/ko/material/receiving-management');
  }, [router]);

  // 입고증 다이얼로그 열기
  const handleOpenReceipt = useCallback(() => {
    setIsReceiptDialogOpen(true);
  }, []);

  // 검사등록 페이지로 이동
  const handleGoToInspection = useCallback(() => {
    router.push('/ko/material/receiving-management/inspection');
  }, [router]);

  // 입고처리 다이얼로그 열기
  const handleOpenReceivingProcessDialog = useCallback(() => {
    setIsReceivingProcessDialogOpen(true);
  }, []);

  // 입고 완료 처리
  const handleReceivingComplete = useCallback((lotNo: string) => {
    setIsReceivingProcessDialogOpen(false);
    setSuccessDialog({ open: true, type: 'receiving', lotNo });
  }, []);

  // 성공 다이얼로그 닫기
  const handleSuccessDialogClose = useCallback(() => {
    setSuccessDialog({ open: false, type: 'receiving' });
    router.push('/ko/material/receiving-management');
  }, [router]);

  if (!detail) {
    return (
      <PageLayout>
        <div className="flex items-center justify-center h-64">
          <p className="text-muted-foreground">데이터를 찾을 수 없습니다.</p>
        </div>
      </PageLayout>
    );
  }

  // 상태별 버튼 구성
  // 검사등록 버튼: 검사대기만
  const showInspectionButton = detail.status === 'inspection_pending';
  // 입고처리 버튼: 발주완료, 배송중만
  const showReceivingProcessButton =
    detail.status === 'order_completed' || detail.status === 'shipping';
  // 입고증 버튼: 검사대기, 입고완료만 (입고대기, 발주완료, 배송중은 없음)
  const showReceiptButton =
    detail.status === 'inspection_pending' || detail.status === 'completed';

  // 입고 정보 표시 여부: 검사대기, 입고대기, 입고완료
  const showReceivingInfo =
    detail.status === 'inspection_pending' ||
    detail.status === 'receiving_pending' ||
    detail.status === 'completed';

  return (
    <PageLayout>
      <div className="space-y-6">
        {/* 헤더 */}
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div className="flex items-center gap-3">
            <Package className="w-6 h-6" />
            <h1 className="text-xl font-semibold">입고 상세</h1>
            <span className="text-lg text-muted-foreground">{detail.orderNo}</span>
            <Badge className={`${RECEIVING_STATUS_STYLES[detail.status]}`}>
              {RECEIVING_STATUS_LABELS[detail.status]}
            </Badge>
          </div>

          <div className="flex items-center gap-2">
            {showReceiptButton && (
              <Button variant="outline" onClick={handleOpenReceipt}>
                <FileText className="w-4 h-4 mr-1.5" />
                입고증
              </Button>
            )}
            <Button variant="outline" onClick={handleGoBack}>
              <List className="w-4 h-4 mr-1.5" />
              목록
            </Button>
            {showInspectionButton && (
              <Button onClick={handleGoToInspection}>
                <ClipboardCheck className="w-4 h-4 mr-1.5" />
                검사등록
              </Button>
            )}
            {showReceivingProcessButton && (
              <Button onClick={handleOpenReceivingProcessDialog}>
                <Download className="w-4 h-4 mr-1.5" />
                입고처리
              </Button>
            )}
          </div>
        </div>

        {/* 발주 정보 */}
        <Card>
          <CardHeader className="pb-4">
            <CardTitle className="text-base">발주 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <div>
                <p className="text-sm text-muted-foreground mb-1">발주번호</p>
                <p className="font-medium">{detail.orderNo}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">발주일자</p>
                <p className="font-medium">{detail.orderDate || '-'}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">공급업체</p>
                <p className="font-medium">{detail.supplier}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">품목코드</p>
                <p className="font-medium">{detail.itemCode}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">품목명</p>
                <p className="font-medium">{detail.itemName}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">규격</p>
                <p className="font-medium">{detail.specification || '-'}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">발주수량</p>
                <p className="font-medium">
                  {detail.orderQty} {detail.orderUnit}
                </p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">납기일</p>
                <p className="font-medium">{detail.dueDate || '-'}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 입고 정보 - 검사대기/입고대기/입고완료 상태에서만 표시 */}
        {showReceivingInfo && (
          <Card>
            <CardHeader className="pb-4">
              <CardTitle className="text-base">입고 정보</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div>
                  <p className="text-sm text-muted-foreground mb-1">입고일자</p>
                  <p className="font-medium">{detail.receivingDate || '-'}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground mb-1">입고수량</p>
                  <p className="font-medium">
                    {detail.receivingQty !== undefined
                      ? `${detail.receivingQty} ${detail.orderUnit}`
                      : '-'}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground mb-1">입고LOT</p>
                  <p className="font-medium">{detail.receivingLot || '-'}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground mb-1">공급업체LOT</p>
                  <p className="font-medium">{detail.supplierLot || '-'}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground mb-1">입고위치</p>
                  <p className="font-medium">{detail.receivingLocation || '-'}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground mb-1">입고담당</p>
                  <p className="font-medium">{detail.receivingManager || '-'}</p>
                </div>
              </div>
            </CardContent>
          </Card>
        )}
      </div>

      {/* 입고증 다이얼로그 */}
      <ReceivingReceiptDialog
        open={isReceiptDialogOpen}
        onOpenChange={setIsReceiptDialogOpen}
        detail={detail}
      />

      {/* 입고처리 다이얼로그 */}
      <ReceivingProcessDialog
        open={isReceivingProcessDialogOpen}
        onOpenChange={setIsReceivingProcessDialogOpen}
        detail={detail}
        onComplete={handleReceivingComplete}
      />

      {/* 성공 다이얼로그 */}
      <SuccessDialog
        open={successDialog.open}
        type={successDialog.type}
        lotNo={successDialog.lotNo}
        onClose={handleSuccessDialogClose}
      />
    </PageLayout>
  );
}