'use client';

/**
 * 출하 상세 페이지
 */

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Truck, FileText, Receipt, ClipboardList, Check, Printer, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogTitle,
} from '@/components/ui/dialog';
import { VisuallyHidden } from '@radix-ui/react-visually-hidden';
import { PageLayout } from '@/components/organisms/PageLayout';
import { mockShipmentDetail } from './mockData';
import {
  SHIPMENT_STATUS_LABELS,
  SHIPMENT_STATUS_STYLES,
  PRIORITY_LABELS,
  PRIORITY_STYLES,
  DELIVERY_METHOD_LABELS,
} from './types';
import { ShippingSlip } from './documents/ShippingSlip';
import { TransactionStatement } from './documents/TransactionStatement';
import { DeliveryConfirmation } from './documents/DeliveryConfirmation';

interface ShipmentDetailProps {
  id: string;
}

export function ShipmentDetail({ id }: ShipmentDetailProps) {
  const router = useRouter();
  const [previewDocument, setPreviewDocument] = useState<'shipping' | 'transaction' | 'delivery' | null>(null);

  // Mock 데이터 사용 (실제로는 API에서 id로 조회)
  const data = mockShipmentDetail;

  // 목록으로 이동
  const handleGoBack = () => {
    router.push('/ko/outbound/shipments');
  };

  // 수정 페이지로 이동
  const handleEdit = () => {
    router.push(`/ko/outbound/shipments/${id}/edit`);
  };

  // 인쇄
  const handlePrint = () => {
    window.print();
  };

  // 정보 영역 렌더링
  const renderInfoField = (label: string, value: React.ReactNode, className?: string) => (
    <div className={className}>
      <div className="text-sm text-muted-foreground mb-1">{label}</div>
      <div className="font-medium">{value}</div>
    </div>
  );

  return (
    <PageLayout>
      <div className="space-y-6">
        {/* 헤더 */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Truck className="w-6 h-6" />
            <h1 className="text-xl font-semibold">출하 상세</h1>
          </div>
          <div className="flex items-center gap-2">
            {/* 문서 미리보기 버튼 */}
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPreviewDocument('shipping')}
            >
              <FileText className="w-4 h-4 mr-1" />
              출고증
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPreviewDocument('transaction')}
            >
              <Receipt className="w-4 h-4 mr-1" />
              거래명세서
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPreviewDocument('delivery')}
            >
              <ClipboardList className="w-4 h-4 mr-1" />
              납품확인서
            </Button>
            <div className="w-px h-6 bg-border mx-2" />
            <Button variant="outline" onClick={handleGoBack}>
              목록
            </Button>
            <Button onClick={handleEdit}>
              수정
            </Button>
          </div>
        </div>

        {/* 메인 콘텐츠 */}
        <div className="space-y-6">
            {/* 출고 정보 */}
            <Card>
              <CardHeader>
                <CardTitle className="text-base">출고 정보</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
                  {renderInfoField('출고번호', data.shipmentNo)}
                  {renderInfoField('출고예정일', data.scheduledDate)}
                  {renderInfoField('로트번호', data.lotNo)}
                  {renderInfoField(
                    '출고상태',
                    <Badge className={SHIPMENT_STATUS_STYLES[data.status]}>
                      {SHIPMENT_STATUS_LABELS[data.status]}
                    </Badge>
                  )}
                  {renderInfoField(
                    '출고 우선순위',
                    <Badge className={PRIORITY_STYLES[data.priority]}>
                      {PRIORITY_LABELS[data.priority]}
                    </Badge>
                  )}
                  {renderInfoField(
                    '배송방식',
                    <Badge variant="outline">
                      {DELIVERY_METHOD_LABELS[data.deliveryMethod]}
                    </Badge>
                  )}
                  {renderInfoField(
                    '입금확인',
                    data.depositConfirmed ? (
                      <span className="flex items-center gap-1 text-green-600">
                        <Check className="w-4 h-4" />
                        확인됨
                      </span>
                    ) : (
                      <span className="text-muted-foreground">미확인</span>
                    )
                  )}
                  {renderInfoField(
                    '세금계산서',
                    data.invoiceIssued ? (
                      <span className="flex items-center gap-1 text-green-600">
                        <Check className="w-4 h-4" />
                        발행됨
                      </span>
                    ) : (
                      <span className="text-muted-foreground">미발행</span>
                    )
                  )}
                  {renderInfoField('거래처 등급', data.customerGrade)}
                  {renderInfoField(
                    '출하가능',
                    data.canShip ? (
                      <span className="flex items-center gap-1 text-green-600">
                        <Check className="w-4 h-4" />
                        가능
                      </span>
                    ) : (
                      <span className="flex items-center gap-1 text-red-600">
                        <X className="w-4 h-4" />
                        불가
                      </span>
                    )
                  )}
                  {renderInfoField('상차담당자', data.loadingManager || '-')}
                  {renderInfoField(
                    '상차완료',
                    data.loadingCompleted ? (
                      <span className="flex items-center gap-1 text-green-600">
                        <Check className="w-4 h-4" />
                        완료 ({data.loadingCompleted})
                      </span>
                    ) : (
                      <span className="text-muted-foreground">-</span>
                    )
                  )}
                  {renderInfoField('등록자', data.registrant || '-')}
                </div>
              </CardContent>
            </Card>

            {/* 발주처/배송 정보 */}
            <Card>
              <CardHeader>
                <CardTitle className="text-base">발주처/배송 정보</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
                  {renderInfoField('발주처', data.customerName)}
                  {renderInfoField('현장명', data.siteName)}
                  {renderInfoField('배송주소', data.deliveryAddress, 'md:col-span-2')}
                  {renderInfoField('인수자', data.receiver || '-')}
                  {renderInfoField('연락처', data.receiverContact || '-')}
                </div>
              </CardContent>
            </Card>

            {/* 출고 품목 */}
            <Card>
              <CardHeader>
                <CardTitle className="text-base">출고 품목</CardTitle>
              </CardHeader>
              <CardContent>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-12 text-center">No</TableHead>
                      <TableHead className="w-24">품목코드</TableHead>
                      <TableHead>품목명</TableHead>
                      <TableHead className="w-24">층/M호</TableHead>
                      <TableHead className="w-28">규격</TableHead>
                      <TableHead className="w-16 text-center">수량</TableHead>
                      <TableHead className="w-36">LOT번호</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {data.products.map((product) => (
                      <TableRow key={product.id}>
                        <TableCell className="text-center">{product.no}</TableCell>
                        <TableCell>{product.itemCode}</TableCell>
                        <TableCell>{product.itemName}</TableCell>
                        <TableCell>{product.floorUnit}</TableCell>
                        <TableCell>{product.specification}</TableCell>
                        <TableCell className="text-center">{product.quantity}</TableCell>
                        <TableCell>{product.lotNo}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>

            {/* 배차 정보 */}
            <Card>
              <CardHeader>
                <CardTitle className="text-base">배차 정보</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
                  {renderInfoField('배송방식', DELIVERY_METHOD_LABELS[data.deliveryMethod])}
                  {renderInfoField('물류사', data.logisticsCompany || '-')}
                  {renderInfoField('차량 톤수', data.vehicleTonnage || '-')}
                  {renderInfoField('운송비', data.shippingCost !== undefined ? `${data.shippingCost.toLocaleString()}원` : '-')}
                </div>
              </CardContent>
            </Card>

            {/* 차량/운전자 정보 */}
            <Card>
              <CardHeader>
                <CardTitle className="text-base">차량/운전자 정보</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
                  {renderInfoField('차량번호', data.vehicleNo || '-')}
                  {renderInfoField('운전자', data.driverName || '-')}
                  {renderInfoField('운전자 연락처', data.driverContact || '-')}
                </div>
              </CardContent>
            </Card>

            {/* 비고 */}
            {data.remarks && (
              <Card>
                <CardHeader>
                  <CardTitle className="text-base">비고</CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-sm whitespace-pre-wrap">{data.remarks}</p>
                </CardContent>
              </Card>
            )}

          </div>

        {/* 문서 미리보기 다이얼로그 - 작업일지 모달 패턴 적용 */}
        <Dialog open={previewDocument !== null} onOpenChange={() => setPreviewDocument(null)}>
          <DialogContent className="sm:max-w-5xl max-h-[90vh] overflow-y-auto p-0 gap-0 bg-gray-100">
            {/* 접근성을 위한 숨겨진 타이틀 */}
            <VisuallyHidden>
              <DialogTitle>
                {previewDocument === 'shipping' && '출고증'}
                {previewDocument === 'transaction' && '거래명세서'}
                {previewDocument === 'delivery' && '납품확인서'}
              </DialogTitle>
            </VisuallyHidden>

            {/* 모달 헤더 - 작업일지 스타일 */}
            <div className="flex items-center justify-between px-6 py-4 border-b bg-white sticky top-0 z-10">
              <div className="flex items-center gap-3">
                <span className="font-semibold text-lg">
                  {previewDocument === 'shipping' && '출고증 미리보기'}
                  {previewDocument === 'transaction' && '거래명세서 미리보기'}
                  {previewDocument === 'delivery' && '납품확인서'}
                </span>
                <span className="text-sm text-muted-foreground">
                  {data.customerName}
                </span>
                <span className="text-sm text-muted-foreground">
                  ({data.shipmentNo})
                </span>
              </div>
              <div className="flex items-center gap-2">
                <Button variant="outline" size="sm" onClick={handlePrint}>
                  <Printer className="w-4 h-4 mr-1.5" />
                  인쇄
                </Button>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-8 w-8"
                  onClick={() => setPreviewDocument(null)}
                >
                  <X className="w-4 h-4" />
                </Button>
              </div>
            </div>

            {/* 문서 본문 - 흰색 카드 형태 */}
            <div className="m-6 p-6 bg-white rounded-lg shadow-sm">
              {previewDocument === 'shipping' && <ShippingSlip data={data} />}
              {previewDocument === 'transaction' && <TransactionStatement data={data} />}
              {previewDocument === 'delivery' && <DeliveryConfirmation data={data} />}
            </div>
          </DialogContent>
        </Dialog>
      </div>
    </PageLayout>
  );
}