'use client';

import { useState } from 'react';
import {
  DocumentViewer,
  DocumentHeader,
  ConstructionApprovalTable,
} from '@/components/document-system';
import { toast } from 'sonner';
import { useRouter } from 'next/navigation';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import type { HandoverReportDetail } from '../types';
import { deleteHandoverReport } from '../actions';
import { formatNumber } from '@/lib/utils/amount';

// 날짜 포맷팅 (년월)
function formatYearMonth(dateStr: string | null): string {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return `${date.getFullYear()}년 ${date.getMonth() + 1}월`;
}

// 날짜 포맷팅 (전체)
function formatDate(dateStr: string | null): string {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date.toLocaleDateString('ko-KR', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });
}

interface HandoverReportDocumentModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  report: HandoverReportDetail;
  onSuccess?: () => void;
}

export function HandoverReportDocumentModal({
  open,
  onOpenChange,
  report,
  onSuccess,
}: HandoverReportDocumentModalProps) {
  const router = useRouter();
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

  // 수정
  const handleEdit = () => {
    onOpenChange(false);
    router.push(`/ko/construction/project/contract/handover-report/${report.id}?mode=edit`);
  };

  // 삭제
  const handleDelete = () => {
    setShowDeleteDialog(true);
  };

  const handleConfirmDelete = async () => {
    const result = await deleteHandoverReport(report.id);
    if (result.success) {
      toast.success('인수인계보고서가 삭제되었습니다.');
      setShowDeleteDialog(false);
      onOpenChange(false);
      onSuccess?.();
    } else {
      toast.error(result.error || '삭제에 실패했습니다.');
    }
  };

  return (
    <>
    <DocumentViewer
      title="인수인계보고서"
      subtitle="인수인계보고서 상세"
      preset="construction"
      open={open}
      onOpenChange={onOpenChange}
      onEdit={handleEdit}
      onDelete={handleDelete}
    >
      <div className="p-8">
            {/* 상단: 제목 + 결재란 (공통 컴포넌트) */}
            <DocumentHeader
              title="인수인계보고서"
              documentCode={report.reportNumber}
              subtitle={`작성일자: ${formatDate(report.createdAt)}`}
              layout="construction"
              customApproval={
                <ConstructionApprovalTable
                  approvers={{
                    writer: { name: '홍길동', department: '부서명' },
                    approver1: { name: '이름', department: '부서명' },
                    approver2: { name: '이름', department: '부서명' },
                    approver3: { name: '이름', department: '부서명' },
                  }}
                />
              }
            />

            {/* 통합 테이블 - 기획서 구조 100% 반영 */}
            <table className="w-full border-collapse border border-gray-300 text-sm">
              <tbody>
                {/* 현장명 */}
                <tr>
                  <th className="border border-gray-300 px-4 py-3 bg-gray-50 text-left w-40 font-medium">현장명</th>
                  <td className="border border-gray-300 px-4 py-3">{report.siteName || '-'}</td>
                </tr>

                {/* 거래처 */}
                <tr>
                  <th className="border border-gray-300 px-4 py-3 bg-gray-50 text-left font-medium">거래처</th>
                  <td className="border border-gray-300 px-4 py-3">{report.partnerName || '-'}</td>
                </tr>

                {/* 준공 */}
                <tr>
                  <th className="border border-gray-300 px-4 py-3 bg-gray-50 text-left font-medium">준공</th>
                  <td className="border border-gray-300 px-4 py-3">{formatYearMonth(report.completionDate)}</td>
                </tr>

                {/* 계약금액 (공급가액) */}
                <tr>
                  <th className="border border-gray-300 px-4 py-3 bg-gray-50 text-left font-medium">계약금액 (공급가액)</th>
                  <td className="border border-gray-300 px-4 py-3">₩ {formatNumber(report.contractAmount)}</td>
                </tr>

                {/* 계약 ITEM - 기획서: 구분, 수량, 비고 3컬럼 */}
                <tr>
                  <th className="border border-gray-300 px-4 py-3 bg-gray-50 text-left font-medium align-middle">계약 ITEM</th>
                  <td className="border border-gray-300 p-0">
                    <table className="w-full border-collapse text-sm">
                      <thead>
                        <tr className="bg-gray-50">
                          <th className="border-b border-gray-300 px-4 py-2 text-left font-medium">구분</th>
                          <th className="border-b border-l border-gray-300 px-4 py-2 text-center font-medium w-24">수량</th>
                          <th className="border-b border-l border-gray-300 px-4 py-2 text-left font-medium">비고</th>
                        </tr>
                      </thead>
                      <tbody>
                        {report.contractItems.length === 0 ? (
                          <tr>
                            <td colSpan={3} className="px-4 py-3 text-center text-gray-400">-</td>
                          </tr>
                        ) : (
                          report.contractItems.map((item, idx) => (
                            <tr key={item.id}>
                              <td className={`px-4 py-2 ${idx > 0 ? 'border-t border-gray-300' : ''}`}>
                                {item.name || '-'}
                              </td>
                              <td className={`px-4 py-2 text-center border-l border-gray-300 ${idx > 0 ? 'border-t' : ''}`}>
                                {formatNumber(item.quantity)}
                              </td>
                              <td className={`px-4 py-2 border-l border-gray-300 ${idx > 0 ? 'border-t' : ''}`}>
                                {item.remark || '-'}
                              </td>
                            </tr>
                          ))
                        )}
                      </tbody>
                    </table>
                  </td>
                </tr>

                {/* 집행유무 - 기획서: 2차 배관 유무, 도장 & 코킹 유무 + 금액 */}
                <tr>
                  <th className="border border-gray-300 px-4 py-3 bg-gray-50 text-left font-medium align-middle">집행유무</th>
                  <td className="border border-gray-300 p-0">
                    <table className="w-full border-collapse text-sm">
                      <tbody>
                        <tr>
                          <th className="px-4 py-2 bg-gray-50 text-left font-medium w-40">2차 배관 유무</th>
                          <td className="px-4 py-2">
                            {report.hasSecondaryPiping
                              ? `포함 (${formatNumber(report.secondaryPipingAmount)})`
                              : '미포함'}
                          </td>
                        </tr>
                        <tr>
                          <th className="border-t border-gray-300 px-4 py-2 bg-gray-50 text-left font-medium">도장 & 코킹 유무</th>
                          <td className="border-t border-gray-300 px-4 py-2">
                            {report.hasCoating
                              ? `포함 (${formatNumber(report.coatingAmount)})`
                              : '미포함'}
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </td>
                </tr>

                {/* 장비 외 실행금액 - 기획서: 운반비, 양중장비, 공과금 */}
                <tr>
                  <th className="border border-gray-300 px-4 py-3 bg-gray-50 text-left font-medium align-middle">장비 외 실행금액</th>
                  <td className="border border-gray-300 px-4 py-3">
                    <div className="space-y-1">
                      <div>운반비 : {formatNumber(report.externalEquipmentCost?.shippingCost)}</div>
                      <div>양중장비 : {formatNumber(report.externalEquipmentCost?.highAltitudeWork)}</div>
                      <div>공과금 : {formatNumber(report.externalEquipmentCost?.publicExpense)}</div>
                    </div>
                  </td>
                </tr>

                {/* 특이사항 - 기획서: 내용 단일 필드 */}
                <tr>
                  <th className="border border-gray-300 px-4 py-3 bg-gray-50 text-left font-medium align-middle">특이사항</th>
                  <td className="border border-gray-300 px-4 py-3 whitespace-pre-wrap">
                    {report.specialNotes || '-'}
                  </td>
                </tr>

                {/* 공사 담당자 - 기획서: 성명, 서명, 미이행 사유 3컬럼 */}
                <tr>
                  <th className="border border-gray-300 px-4 py-3 bg-gray-50 text-left font-medium align-middle">공사 담당자</th>
                  <td className="border border-gray-300 p-0">
                    <table className="w-full border-collapse text-sm">
                      <thead>
                        <tr className="bg-gray-50">
                          <th className="border-b border-gray-300 px-4 py-2 text-center font-medium w-28">성명</th>
                          <th className="border-b border-l border-gray-300 px-4 py-2 text-center font-medium">서명</th>
                          <th className="border-b border-l border-gray-300 px-4 py-2 text-center font-medium w-32">미이행 사유</th>
                        </tr>
                      </thead>
                      <tbody>
                        {report.constructionManagers.length === 0 ? (
                          <tr>
                            <td colSpan={3} className="px-4 py-3 text-center text-gray-400">-</td>
                          </tr>
                        ) : (
                          report.constructionManagers.map((manager, idx) => (
                            <tr key={manager.id}>
                              <td className={`px-4 py-2 text-center ${idx > 0 ? 'border-t border-gray-300' : ''}`}>
                                {manager.name || '-'}
                              </td>
                              <td className={`px-4 py-2 text-center border-l border-gray-300 ${idx > 0 ? 'border-t' : ''}`}>
                                {manager.signature || ''}
                              </td>
                              <td className={`px-4 py-2 text-center border-l border-gray-300 ${idx > 0 ? 'border-t' : ''}`}>
                                {manager.nonPerformanceReason || ''}
                              </td>
                            </tr>
                          ))
                        )}
                      </tbody>
                    </table>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
    </DocumentViewer>

    <DeleteConfirmDialog
      open={showDeleteDialog}
      onOpenChange={setShowDeleteDialog}
      description="이 인수인계보고서를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
      onConfirm={handleConfirmDelete}
    />
    </>
  );
}