'use client';

import { useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import type {
  ProgressBillingDetail,
  ProgressBillingDetailFormData,
  ProgressBillingItem,
} from '../types';
import {
  progressBillingDetailToFormData,
  MOCK_PROGRESS_BILLING_DETAIL,
} from '../types';

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

export function useProgressBillingDetailForm({
  mode,
  billingId,
  initialData,
}: UseProgressBillingDetailFormProps) {
  const router = useRouter();

  // Mode flags
  const isViewMode = mode === 'view';
  const isEditMode = mode === 'edit';

  // Form data state
  const [formData, setFormData] = useState<ProgressBillingDetailFormData>(() => {
    if (initialData) {
      return progressBillingDetailToFormData(initialData);
    }
    // 목업 데이터 사용
    return progressBillingDetailToFormData(MOCK_PROGRESS_BILLING_DETAIL);
  });

  // Loading state
  const [isLoading, setIsLoading] = useState(false);

  // Dialog states
  const [showSaveDialog, setShowSaveDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

  // Selection states for billing items
  const [selectedBillingItems, setSelectedBillingItems] = useState<Set<string>>(new Set());

  // Selection states for photo items
  const [selectedPhotoItems, setSelectedPhotoItems] = useState<Set<string>>(new Set());

  // Modal states
  const [showDirectConstructionModal, setShowDirectConstructionModal] = useState(false);
  const [showIndirectConstructionModal, setShowIndirectConstructionModal] = useState(false);
  const [showPhotoDocumentModal, setShowPhotoDocumentModal] = useState(false);

  // Navigation handlers
  const handleBack = useCallback(() => {
    router.push('/construction/billing/progress-billing-management');
  }, [router]);

  const handleEdit = useCallback(() => {
    router.push('/construction/billing/progress-billing-management/' + billingId + '?mode=edit');
  }, [router, billingId]);

  const handleCancel = useCallback(() => {
    router.push('/construction/billing/progress-billing-management/' + billingId + '?mode=view');
  }, [router, billingId]);

  // Form handlers
  const handleFieldChange = useCallback(
    (field: keyof ProgressBillingDetailFormData, value: string | number) => {
      setFormData((prev) => ({
        ...prev,
        [field]: value,
      }));
    },
    []
  );

  // Save handlers
  const handleSave = useCallback(() => {
    setShowSaveDialog(true);
  }, []);

  const handleConfirmSave = useCallback(async () => {
    setIsLoading(true);
    try {
      // TODO: API 호출
      await new Promise((resolve) => setTimeout(resolve, 500));
      setShowSaveDialog(false);
      router.push('/construction/billing/progress-billing-management/' + billingId + '?mode=view');
    } catch (error) {
      console.error('Save failed:', error);
    } finally {
      setIsLoading(false);
    }
  }, [formData, router, billingId]);

  // Delete handlers
  const handleDelete = useCallback(() => {
    setShowDeleteDialog(true);
  }, []);

  const handleConfirmDelete = useCallback(async () => {
    setIsLoading(true);
    try {
      // TODO: API 호출
      await new Promise((resolve) => setTimeout(resolve, 500));
      setShowDeleteDialog(false);
      router.push('/construction/billing/progress-billing-management');
    } catch (error) {
      console.error('Delete failed:', error);
    } finally {
      setIsLoading(false);
    }
  }, [router, billingId]);

  // Billing item handlers
  const handleBillingItemChange = useCallback(
    (itemId: string, field: keyof ProgressBillingItem, value: string | number) => {
      setFormData((prev) => ({
        ...prev,
        billingItems: prev.billingItems.map((item) =>
          item.id === itemId ? { ...item, [field]: value } : item
        ),
      }));
    },
    []
  );

  const handleToggleBillingItemSelection = useCallback((itemId: string) => {
    setSelectedBillingItems((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(itemId)) {
        newSet.delete(itemId);
      } else {
        newSet.add(itemId);
      }
      return newSet;
    });
  }, []);

  const handleToggleSelectAllBillingItems = useCallback(() => {
    setSelectedBillingItems((prev) => {
      if (prev.size === formData.billingItems.length) {
        return new Set();
      }
      return new Set(formData.billingItems.map((item) => item.id));
    });
  }, [formData.billingItems]);

  const handleApplySelectedBillingItems = useCallback(() => {
    // 선택된 항목의 변경사항 적용 (현재는 선택 해제만)
    setSelectedBillingItems(new Set());
  }, []);

  // Photo item handlers
  const handleTogglePhotoItemSelection = useCallback((itemId: string) => {
    setSelectedPhotoItems((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(itemId)) {
        newSet.delete(itemId);
      } else {
        newSet.add(itemId);
      }
      return newSet;
    });
  }, []);

  const handleToggleSelectAllPhotoItems = useCallback(() => {
    setSelectedPhotoItems((prev) => {
      if (prev.size === formData.photoItems.length) {
        return new Set();
      }
      return new Set(formData.photoItems.map((item) => item.id));
    });
  }, [formData.photoItems]);

  const handleApplySelectedPhotoItems = useCallback(() => {
    // 선택된 항목의 변경사항 적용 (현재는 선택 해제만)
    setSelectedPhotoItems(new Set());
  }, []);

  // Photo select handler (라디오 버튼으로 사진 선택)
  const handlePhotoSelect = useCallback((itemId: string, photoIndex: number) => {
    setFormData((prev) => ({
      ...prev,
      photoItems: prev.photoItems.map((item) =>
        item.id === itemId ? { ...item, selectedPhotoIndex: photoIndex } : item
      ),
    }));
  }, []);

  // Modal handlers
  const handleViewDirectConstruction = useCallback(() => {
    setShowDirectConstructionModal(true);
  }, []);

  const handleViewIndirectConstruction = useCallback(() => {
    setShowIndirectConstructionModal(true);
  }, []);

  const handleViewPhotoDocument = useCallback(() => {
    setShowPhotoDocumentModal(true);
  }, []);

  return {
    // Mode flags
    isViewMode,
    isEditMode,

    // Form data
    formData,

    // Loading state
    isLoading,

    // Dialog states
    showSaveDialog,
    setShowSaveDialog,
    showDeleteDialog,
    setShowDeleteDialog,

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

    // Selection states
    selectedBillingItems,
    selectedPhotoItems,

    // Navigation handlers
    handleBack,
    handleEdit,
    handleCancel,

    // Form handlers
    handleFieldChange,

    // CRUD handlers
    handleSave,
    handleConfirmSave,
    handleDelete,
    handleConfirmDelete,

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

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

    // Modal handlers
    handleViewDirectConstruction,
    handleViewIndirectConstruction,
    handleViewPhotoDocument,
  };
}
