'use client';

import { useState, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import type {
  OrderDetail,
  OrderDetailFormData,
  OrderDetailItem,
  OrderDetailCategory,
} from '../types';
import {
  getEmptyOrderDetailItem,
  getEmptyOrderDetailCategory,
  getEmptyOrderDetailFormData,
  orderDetailToFormData,
} from '../types';
import { updateOrder, deleteOrder, duplicateOrder } from '../actions';
import type { ScheduleEvent } from '@/components/common/ScheduleCalendar';

interface UseOrderDetailFormProps {
  mode: 'view' | 'edit';
  orderId: string;
  initialData?: OrderDetail;
}

interface UseOrderDetailFormReturn {
  // Mode flags
  isViewMode: boolean;
  isEditMode: boolean;

  // Form data
  formData: OrderDetailFormData;

  // Loading state
  isLoading: boolean;

  // Dialog states
  showDeleteDialog: boolean;
  setShowDeleteDialog: (show: boolean) => void;
  showSaveDialog: boolean;
  setShowSaveDialog: (show: boolean) => void;
  showCategoryDeleteDialog: string | null;
  setShowCategoryDeleteDialog: (categoryId: string | null) => void;

  // Modal states
  showDocumentModal: boolean;
  setShowDocumentModal: (show: boolean) => void;

  // Selection states
  selectedItems: Map<string, Set<string>>;
  addCounts: Map<string, number>;
  setAddCounts: React.Dispatch<React.SetStateAction<Map<string, number>>>;
  categoryFilters: Map<string, string>;

  // Calendar states
  calendarDate: Date;
  selectedCalendarDate: Date | null;
  calendarEvents: ScheduleEvent[];

  // Navigation handlers
  handleBack: () => void;
  handleEdit: () => void;
  handleCancel: () => void;

  // Form handlers
  handleFieldChange: (
    field: keyof OrderDetailFormData,
    value: string | number | boolean | string[] | OrderDetailCategory[]
  ) => void;

  // CRUD handlers
  handleSave: () => void;
  handleConfirmSave: () => Promise<void>;
  handleDelete: () => void;
  handleConfirmDelete: () => Promise<void>;
  handleDuplicate: () => Promise<void>;
  handleViewDocument: () => void;

  // Category handlers
  handleAddCategory: () => void;
  handleDeleteCategory: (categoryId: string) => void;
  handleConfirmDeleteCategory: () => void;
  handleCategoryChange: (
    categoryId: string,
    field: keyof OrderDetailCategory,
    value: string
  ) => void;

  // Item handlers
  handleAddItems: (categoryId: string, count: number) => void;
  handleDeleteSelectedItems: (categoryId: string) => void;
  handleDeleteAllItems: (categoryId: string) => void;
  handleItemChange: (
    categoryId: string,
    itemId: string,
    field: keyof OrderDetailItem,
    value: string | number
  ) => void;

  // Selection handlers
  handleToggleSelection: (categoryId: string, itemId: string) => void;
  handleToggleSelectAll: (categoryId: string, items: OrderDetailItem[]) => void;

  // Calendar handlers
  handleCalendarDateClick: (date: Date) => void;
  handleCalendarMonthChange: (date: Date) => void;
}

export function useOrderDetailForm({
  mode,
  orderId,
  initialData,
}: UseOrderDetailFormProps): UseOrderDetailFormReturn {
  const router = useRouter();
  const isViewMode = mode === 'view';
  const isEditMode = mode === 'edit';

  // Form data
  const [formData, setFormData] = useState<OrderDetailFormData>(
    initialData ? orderDetailToFormData(initialData) : getEmptyOrderDetailFormData()
  );

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

  // Dialog states
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [showSaveDialog, setShowSaveDialog] = useState(false);
  const [showCategoryDeleteDialog, setShowCategoryDeleteDialog] = useState<string | null>(null);

  // Modal states
  const [showDocumentModal, setShowDocumentModal] = useState(false);

  // Category table selection states
  const [selectedItems, setSelectedItems] = useState<Map<string, Set<string>>>(new Map());

  // Category add counts
  const [addCounts, setAddCounts] = useState<Map<string, number>>(new Map());

  // Category filters
  const [categoryFilters, _setCategoryFilters] = useState<Map<string, string>>(new Map());

  // Calendar states
  const [calendarDate, setCalendarDate] = useState<Date>(new Date());
  const [selectedCalendarDate, setSelectedCalendarDate] = useState<Date | null>(null);

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

  const handleEdit = useCallback(() => {
    router.push(`/ko/construction/order/order-management/${orderId}?mode=edit`);
  }, [router, orderId]);

  const handleCancel = useCallback(() => {
    router.push(`/ko/construction/order/order-management/${orderId}?mode=view`);
  }, [router, orderId]);

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

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

  const handleConfirmSave = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await updateOrder(orderId, formData);
      if (result.success) {
        toast.success('수정이 완료되었습니다.');
        setShowSaveDialog(false);
        router.push(`/ko/construction/order/order-management/${orderId}?mode=view`);
        router.refresh();
      } else {
        toast.error(result.error || '저장에 실패했습니다.');
      }
    } catch (error) {
      toast.error(error instanceof Error ? error.message : '저장에 실패했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, [router, orderId, formData]);

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

  const handleConfirmDelete = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await deleteOrder(orderId);
      if (result.success) {
        toast.success('발주가 삭제되었습니다.');
        setShowDeleteDialog(false);
        router.push('/ko/construction/order/order-management');
        router.refresh();
      } else {
        toast.error(result.error || '삭제에 실패했습니다.');
      }
    } catch (error) {
      toast.error(error instanceof Error ? error.message : '삭제에 실패했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, [router, orderId]);

  // ============================================
  // Duplicate handler
  // ============================================
  const handleDuplicate = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await duplicateOrder(orderId);
      if (result.success && result.newId) {
        toast.success('발주가 복제되었습니다.');
        router.push(`/ko/construction/order/order-management/${result.newId}?mode=edit`);
      } else {
        toast.error(result.error || '복제에 실패했습니다.');
      }
    } catch (error) {
      toast.error(error instanceof Error ? error.message : '복제에 실패했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, [router, orderId]);

  // ============================================
  // Document modal handler
  // ============================================
  const handleViewDocument = useCallback(() => {
    setShowDocumentModal(true);
  }, []);

  // ============================================
  // Category handlers
  // ============================================
  const handleAddCategory = useCallback(() => {
    const newCategory = getEmptyOrderDetailCategory();
    setFormData((prev) => ({
      ...prev,
      orderCategories: [...prev.orderCategories, newCategory],
    }));
  }, []);

  const handleDeleteCategory = useCallback((categoryId: string) => {
    setShowCategoryDeleteDialog(categoryId);
  }, []);

  const handleConfirmDeleteCategory = useCallback(() => {
    if (showCategoryDeleteDialog) {
      setFormData((prev) => ({
        ...prev,
        orderCategories: prev.orderCategories.filter(
          (cat) => cat.id !== showCategoryDeleteDialog
        ),
      }));
      setSelectedItems((prev) => {
        const newMap = new Map(prev);
        newMap.delete(showCategoryDeleteDialog);
        return newMap;
      });
      setShowCategoryDeleteDialog(null);
    }
  }, [showCategoryDeleteDialog]);

  const handleCategoryChange = useCallback(
    (categoryId: string, field: keyof OrderDetailCategory, value: string) => {
      setFormData((prev) => ({
        ...prev,
        orderCategories: prev.orderCategories.map((cat) =>
          cat.id === categoryId ? { ...cat, [field]: value } : cat
        ),
      }));
    },
    []
  );

  // ============================================
  // Item handlers
  // ============================================
  const handleAddItems = useCallback((categoryId: string, count: number) => {
    if (count <= 0) {
      toast.warning('추가할 개수를 입력해주세요.');
      return;
    }
    const newItems: OrderDetailItem[] = Array.from({ length: count }, () => ({
      ...getEmptyOrderDetailItem(),
      id: String(Date.now() + Math.random()),
    }));

    setFormData((prev) => ({
      ...prev,
      orderCategories: prev.orderCategories.map((cat) =>
        cat.id === categoryId ? { ...cat, items: [...cat.items, ...newItems] } : cat
      ),
    }));
    setAddCounts((prev) => {
      const newMap = new Map(prev);
      newMap.set(categoryId, 1);
      return newMap;
    });
  }, []);

  const handleDeleteSelectedItems = useCallback(
    (categoryId: string) => {
      const selected = selectedItems.get(categoryId);
      if (!selected || selected.size === 0) {
        toast.warning('삭제할 항목을 선택해주세요.');
        return;
      }

      setFormData((prev) => ({
        ...prev,
        orderCategories: prev.orderCategories.map((cat) =>
          cat.id === categoryId
            ? { ...cat, items: cat.items.filter((item) => !selected.has(item.id)) }
            : cat
        ),
      }));
      setSelectedItems((prev) => {
        const newMap = new Map(prev);
        newMap.set(categoryId, new Set());
        return newMap;
      });
    },
    [selectedItems]
  );

  const handleDeleteAllItems = useCallback((categoryId: string) => {
    setFormData((prev) => ({
      ...prev,
      orderCategories: prev.orderCategories.map((cat) =>
        cat.id === categoryId ? { ...cat, items: [] } : cat
      ),
    }));
    setSelectedItems((prev) => {
      const newMap = new Map(prev);
      newMap.set(categoryId, new Set());
      return newMap;
    });
  }, []);

  const handleItemChange = useCallback(
    (
      categoryId: string,
      itemId: string,
      field: keyof OrderDetailItem,
      value: string | number
    ) => {
      setFormData((prev) => ({
        ...prev,
        orderCategories: prev.orderCategories.map((cat) =>
          cat.id === categoryId
            ? {
                ...cat,
                items: cat.items.map((item) =>
                  item.id === itemId ? { ...item, [field]: value } : item
                ),
              }
            : cat
        ),
      }));
    },
    []
  );

  // ============================================
  // Selection handlers
  // ============================================
  const handleToggleSelection = useCallback((categoryId: string, itemId: string) => {
    setSelectedItems((prev) => {
      const newMap = new Map(prev);
      const categorySet = newMap.get(categoryId) || new Set();
      const newSet = new Set(categorySet);
      if (newSet.has(itemId)) {
        newSet.delete(itemId);
      } else {
        newSet.add(itemId);
      }
      newMap.set(categoryId, newSet);
      return newMap;
    });
  }, []);

  const handleToggleSelectAll = useCallback(
    (categoryId: string, items: OrderDetailItem[]) => {
      setSelectedItems((prev) => {
        const newMap = new Map(prev);
        const categorySet = newMap.get(categoryId) || new Set();
        if (categorySet.size === items.length) {
          newMap.set(categoryId, new Set());
        } else {
          newMap.set(categoryId, new Set(items.map((item) => item.id)));
        }
        return newMap;
      });
    },
    []
  );

  // ============================================
  // Calendar handlers
  // ============================================
  const calendarEvents: ScheduleEvent[] = useMemo(() => {
    if (!initialData?.scheduleEvents) return [];
    return initialData.scheduleEvents.map((event) => ({
      id: event.id,
      title: event.title,
      startDate: event.startDate,
      endDate: event.endDate,
      color: event.color,
      status: 'order_complete' as const,
      data: event,
    }));
  }, [initialData?.scheduleEvents]);

  const handleCalendarDateClick = useCallback((date: Date) => {
    setSelectedCalendarDate((prev) => {
      if (prev && prev.getTime() === date.getTime()) {
        return null;
      }
      return date;
    });
  }, []);

  const handleCalendarMonthChange = useCallback((date: Date) => {
    setCalendarDate(date);
  }, []);

  return {
    // Mode flags
    isViewMode,
    isEditMode,

    // Form data
    formData,

    // Loading state
    isLoading,

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

    // Modal states
    showDocumentModal,
    setShowDocumentModal,

    // Selection states
    selectedItems,
    addCounts,
    setAddCounts,
    categoryFilters,

    // Calendar states
    calendarDate,
    selectedCalendarDate,
    calendarEvents,

    // Navigation handlers
    handleBack,
    handleEdit,
    handleCancel,

    // Form handlers
    handleFieldChange,

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

    // Category handlers
    handleAddCategory,
    handleDeleteCategory,
    handleConfirmDeleteCategory,
    handleCategoryChange,

    // Item handlers
    handleAddItems,
    handleDeleteSelectedItems,
    handleDeleteAllItems,
    handleItemChange,

    // Selection handlers
    handleToggleSelection,
    handleToggleSelectAll,

    // Calendar handlers
    handleCalendarDateClick,
    handleCalendarMonthChange,
  };
}