'use client';

import { useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { Hammer, Wrench, Image } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { progressBillingConfig } from './progressBillingConfig';
import { toast } from 'sonner';
import type { ProgressBillingDetail } from './types';
import { useProgressBillingDetailForm } from './hooks/useProgressBillingDetailForm';
import { ProgressBillingInfoCard } from './cards/ProgressBillingInfoCard';
import { ContractInfoCard } from './cards/ContractInfoCard';
import { ProgressBillingItemTable } from './tables/ProgressBillingItemTable';
import { PhotoTable } from './tables/PhotoTable';
import { DirectConstructionModal } from './modals/DirectConstructionModal';
import { IndirectConstructionModal } from './modals/IndirectConstructionModal';
import { PhotoDocumentModal } from './modals/PhotoDocumentModal';

interface ProgressBillingDetailFormProps {
  mode: 'view' | 'edit';
  billingId: string;
  initialData?: ProgressBillingDetail;
}

export default function ProgressBillingDetailForm({
  mode,
  billingId,
  initialData,
}: ProgressBillingDetailFormProps) {
  const router = useRouter();

  const {
    // Mode flags
    isViewMode,
    isEditMode,

    // Form data
    formData,

    // Modal states
    showDirectConstructionModal,
    setShowDirectConstructionModal,
    showIndirectConstructionModal,
    setShowIndirectConstructionModal,
    showPhotoDocumentModal,
    setShowPhotoDocumentModal,

    // Selection states
    selectedBillingItems,
    selectedPhotoItems,

    // Form handlers
    handleFieldChange,

    // Billing item handlers
    handleBillingItemChange,
    handleToggleBillingItemSelection,
    handleToggleSelectAllBillingItems,
    handleApplySelectedBillingItems,

    // Photo item handlers
    handleTogglePhotoItemSelection,
    handleToggleSelectAllPhotoItems,
    handleApplySelectedPhotoItems,
    handlePhotoSelect,

    // Modal handlers
    handleViewDirectConstruction,
    handleViewIndirectConstruction,
    handleViewPhotoDocument,
  } = useProgressBillingDetailForm({ mode, billingId, initialData });

  // 저장 핸들러 (IntegratedDetailTemplate용)
  const handleSubmit = useCallback(async (): Promise<{ success: boolean; error?: string }> => {
    try {
      // TODO: API 호출
      await new Promise((resolve) => setTimeout(resolve, 500));
      toast.success('저장되었습니다.');
      router.push('/ko/construction/billing/progress-billing-management/' + billingId + '?mode=view');
      return { success: true };
    } catch (error) {
      console.error('Save failed:', error);
      return { success: false, error: '저장에 실패했습니다.' };
    }
  }, [formData, router, billingId]);

  // 커스텀 헤더 액션 (view 모드에서 직접/간접 공사 내역, 사진대지 버튼)
  const customHeaderActions = useMemo(() => {
    if (!isViewMode) return null;
    return (
      <>
        <Button variant="outline" onClick={handleViewDirectConstruction} size="sm">
          <Hammer className="h-4 w-4 md:mr-2" />
          <span className="hidden md:inline">직접 공사 내역 보기</span>
        </Button>
        <Button variant="outline" onClick={handleViewIndirectConstruction} size="sm">
          <Wrench className="h-4 w-4 md:mr-2" />
          <span className="hidden md:inline">간접 공사 내역 보기</span>
        </Button>
        <Button variant="outline" onClick={handleViewPhotoDocument} size="sm">
          <Image className="h-4 w-4 md:mr-2" />
          <span className="hidden md:inline">사진대지 보기</span>
        </Button>
      </>
    );
  }, [isViewMode, handleViewDirectConstruction, handleViewIndirectConstruction, handleViewPhotoDocument]);

  // 폼 내용 렌더링 함수 (IntegratedDetailTemplate용)
  const renderFormContent = () => (
    <div className="space-y-6">
        {/* 기성청구 정보 */}
        <ProgressBillingInfoCard
          formData={formData}
          isViewMode={isViewMode}
          onFieldChange={handleFieldChange}
        />

        {/* 계약 정보 */}
        <ContractInfoCard formData={formData} />

        {/* 기성청구 내역 */}
        <ProgressBillingItemTable
          items={formData.billingItems}
          isViewMode={isViewMode}
          isEditMode={isEditMode}
          selectedItems={selectedBillingItems}
          onToggleSelection={handleToggleBillingItemSelection}
          onToggleSelectAll={handleToggleSelectAllBillingItems}
          onApplySelected={handleApplySelectedBillingItems}
          onItemChange={handleBillingItemChange}
        />

        {/* 사진대지 */}
        <PhotoTable
          items={formData.photoItems}
          isViewMode={isViewMode}
          isEditMode={isEditMode}
          selectedItems={selectedPhotoItems}
          onToggleSelection={handleTogglePhotoItemSelection}
          onToggleSelectAll={handleToggleSelectAllPhotoItems}
          onApplySelected={handleApplySelectedPhotoItems}
          onPhotoSelect={handlePhotoSelect}
        />
    </div>
  );

  // 동적 config 설정
  // IntegratedDetailTemplate: create → "{title} 등록", view → "{title}", edit → "{title} 수정"
  // view 모드에서 "기성청구 상세"로 표시하려면 직접 설정 필요
  const dynamicConfig = {
    ...progressBillingConfig,
    title: isViewMode ? '기성청구 상세' : '기성청구',
  };

  return (
    <>
      <IntegratedDetailTemplate
        config={dynamicConfig}
        mode={mode}
        initialData={{}}
        itemId={billingId}
        isLoading={false}
        onSubmit={handleSubmit}
        headerActions={customHeaderActions}
        renderView={() => renderFormContent()}
        renderForm={() => renderFormContent()}
      />

      {/* 직접 공사 내역서 모달 (특수 기능) */}
      <DirectConstructionModal
        open={showDirectConstructionModal}
        onOpenChange={setShowDirectConstructionModal}
        data={formData}
      />

      {/* 간접 공사 내역서 모달 (특수 기능) */}
      <IndirectConstructionModal
        open={showIndirectConstructionModal}
        onOpenChange={setShowIndirectConstructionModal}
        data={formData}
      />

      {/* 사진대지 모달 (특수 기능) */}
      <PhotoDocumentModal
        open={showPhotoDocumentModal}
        onOpenChange={setShowPhotoDocumentModal}
        data={formData}
      />
    </>
  );
}
