'use client';

import { useState, useMemo, useCallback, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useDateRange } from '@/hooks';
import { DollarSign, Plus } from 'lucide-react';
import { TableCell, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { toast } from 'sonner';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import type { PricingTable, TradeGrade } from './types';
import {
  getPricingTableList,
  getPricingTableStats,
  deletePricingTable,
  deletePricingTables,
} from './actions';
import { formatNumber } from '@/lib/utils/amount';

export default function PricingTableListClient() {
  const router = useRouter();

  // ===== 상태 =====
  const [allItems, setAllItems] = useState<PricingTable[]>([]);
  const [_stats, setStats] = useState({ total: 0, active: 0, inactive: 0 });
  const [isLoading, setIsLoading] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);

  // 날짜 범위
  const { startDate, endDate, setStartDate, setEndDate } = useDateRange('currentYear');

  // 검색어
  const [searchQuery, setSearchQuery] = useState('');

  // 거래등급 필터
  const [selectedGrade, setSelectedGrade] = useState<TradeGrade>('A등급');

  // ===== 데이터 로드 =====
  const loadData = useCallback(async () => {
    setIsLoading(true);
    try {
      const [listResult, statsResult] = await Promise.all([
        getPricingTableList({ size: 1000 }),
        getPricingTableStats(),
      ]);

      if (listResult.success && listResult.data) {
        setAllItems(listResult.data.items);
      }
      if (statsResult.success && statsResult.data) {
        setStats(statsResult.data);
      }
    } catch {
      toast.error('데이터 로드에 실패했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    loadData();
  }, [loadData]);

  // ===== 핸들러 =====
  const handleRowClick = useCallback(
    (item: PricingTable) => {
      router.push(`/ko/master-data/pricing-table-management/${item.id}?mode=view`);
    },
    [router]
  );

  const handleCreate = useCallback(() => {
    router.push('/ko/master-data/pricing-table-management?mode=new');
  }, [router]);

  const handleDeleteConfirm = useCallback(async () => {
    if (!deleteTargetId) return;

    setIsLoading(true);
    try {
      const result = await deletePricingTable(deleteTargetId);
      if (result.success) {
        toast.success('단가표가 삭제되었습니다.');
        setAllItems((prev) => prev.filter((p) => p.id !== deleteTargetId));
      } else {
        toast.error(result.error || '삭제에 실패했습니다.');
      }
    } catch {
      toast.error('삭제 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
      setDeleteDialogOpen(false);
      setDeleteTargetId(null);
    }
  }, [deleteTargetId]);

  const handleBulkDelete = useCallback(
    async (selectedIds: string[]) => {
      if (selectedIds.length === 0) {
        toast.warning('삭제할 항목을 선택해주세요.');
        return;
      }

      setIsLoading(true);
      try {
        const result = await deletePricingTables(selectedIds);
        if (result.success) {
          toast.success(`${result.deletedCount}개 항목이 삭제되었습니다.`);
          await loadData();
        } else {
          toast.error(result.error || '일괄 삭제에 실패했습니다.');
        }
      } catch {
        toast.error('일괄 삭제 중 오류가 발생했습니다.');
      } finally {
        setIsLoading(false);
      }
    },
    [loadData]
  );

  // 해당 거래등급의 마진율/판매단가 가져오기
  const getGradePricing = useCallback(
    (item: PricingTable) => {
      return item.gradePricings.find((gp) => gp.grade === selectedGrade);
    },
    [selectedGrade]
  );

  // ===== Config =====
  const config: UniversalListConfig<PricingTable> = useMemo(
    () => ({
      title: '단가표 목록',
      icon: DollarSign,
      basePath: '/master-data/pricing-table-management',

      idField: 'id',

      actions: {
        getList: async () => {
          try {
            const [listResult, statsResult] = await Promise.all([
              getPricingTableList({ size: 1000 }),
              getPricingTableStats(),
            ]);

            if (listResult.success && listResult.data) {
              setAllItems(listResult.data.items);
              if (statsResult.success && statsResult.data) {
                setStats(statsResult.data);
              }
              return {
                success: true,
                data: listResult.data.items,
                totalCount: listResult.data.items.length,
                totalPages: 1,
              };
            }
            return { success: false, error: '데이터 로드에 실패했습니다.' };
          } catch {
            return { success: false, error: '서버 오류가 발생했습니다.' };
          }
        },
        deleteItem: async (id: string) => {
          const result = await deletePricingTable(id);
          return { success: result.success, error: result.error };
        },
        deleteBulk: async (ids: string[]) => {
          const result = await deletePricingTables(ids);
          return { success: result.success, error: result.error };
        },
      },

      columns: [
        { key: 'no', label: '번호', className: 'w-[50px] text-center' },
        { key: 'pricingCode', label: '단가번호', className: 'w-[100px]', copyable: true },
        { key: 'itemCode', label: '품목코드', className: 'w-[100px]', copyable: true },
        { key: 'itemType', label: '품목유형', className: 'w-[80px]' },
        { key: 'itemName', label: '품목명', className: 'min-w-[120px]', copyable: true },
        { key: 'specification', label: '규격', className: 'w-[70px]', copyable: true },
        { key: 'unit', label: '단위', className: 'w-[50px] text-center', copyable: true },
        { key: 'purchasePrice', label: '매입단가', className: 'w-[90px] text-right', copyable: true },
        { key: 'processingCost', label: '가공비', className: 'w-[80px] text-right', copyable: true },
        { key: 'marginRate', label: '마진율', className: 'w-[70px] text-right', copyable: true },
        { key: 'sellingPrice', label: '판매단가', className: 'w-[90px] text-right', copyable: true },
        { key: 'status', label: '상태', className: 'w-[70px] text-center' },
        { key: 'author', label: '작성자', className: 'w-[80px] text-center', copyable: true },
        { key: 'changedDate', label: '변경일', className: 'w-[100px] text-center', copyable: true },
      ],

      clientSideFiltering: true,
      itemsPerPage: 20,

      hideSearch: true,
      searchValue: searchQuery,
      onSearchChange: setSearchQuery,

      dateRangeSelector: {
        enabled: true,
        showPresets: true,
        startDate,
        endDate,
        onStartDateChange: setStartDate,
        onEndDateChange: setEndDate,
      },

      filterConfig: [
        {
          key: 'status',
          label: '상태',
          type: 'single' as const,
          options: [
            { value: '사용', label: '사용' },
            { value: '미사용', label: '미사용' },
          ],
          allOptionLabel: '전체',
        },
      ],
      initialFilters: { status: '' },

      customFilterFn: (items: PricingTable[], filterValues: Record<string, string | string[]>) => {
        const statusFilter = filterValues.status as string;
        if (!statusFilter) return items;
        return items.filter((item) => item.status === statusFilter);
      },

      searchFilter: (item, searchValue) => {
        if (!searchValue || !searchValue.trim()) return true;
        const search = searchValue.toLowerCase().trim();
        return (
          item.pricingCode.toLowerCase().includes(search) ||
          item.itemCode.toLowerCase().includes(search) ||
          item.itemName.toLowerCase().includes(search) ||
          item.itemType.toLowerCase().includes(search)
        );
      },

      createButton: {
        label: '단가표 등록',
        onClick: handleCreate,
        icon: Plus,
      },

      onBulkDelete: handleBulkDelete,

      // 테이블 위 커스텀 영역 (거래등급 배지 필터)
      renderCustomHeader: () => (
        <div className="flex items-center gap-2">
          {(['A등급', 'B등급', 'C등급', 'D등급'] as TradeGrade[]).map((grade) => (
            <Badge
              key={grade}
              variant={selectedGrade === grade ? 'default' : 'outline'}
              className="cursor-pointer"
              onClick={() => setSelectedGrade(grade)}
            >
              {grade}
            </Badge>
          ))}
        </div>
      ),

      renderTableRow: (
        item: PricingTable,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<PricingTable>
      ) => {
        const gp = getGradePricing(item);
        return (
          <TableRow
            key={item.id}
            className={`cursor-pointer hover:bg-muted/50 ${handlers.isSelected ? 'bg-blue-50' : ''}`}
            onClick={() => handleRowClick(item)}
          >
            <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
              <Checkbox checked={handlers.isSelected} onCheckedChange={handlers.onToggle} />
            </TableCell>
            <TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
            <TableCell className="font-mono text-sm">{item.pricingCode}</TableCell>
            <TableCell className="font-mono text-sm">{item.itemCode}</TableCell>
            <TableCell>{item.itemType}</TableCell>
            <TableCell className="font-medium">{item.itemName}</TableCell>
            <TableCell>{item.specification}</TableCell>
            <TableCell className="text-center">{item.unit}</TableCell>
            <TableCell className="text-right">{formatNumber(item.purchasePrice)}</TableCell>
            <TableCell className="text-right">{formatNumber(item.processingCost)}</TableCell>
            <TableCell className="text-right">{gp ? `${gp.marginRate}%` : '-'}</TableCell>
            <TableCell className="text-right">{gp ? formatNumber(gp.sellingPrice) : '-'}</TableCell>
            <TableCell className="text-center">
              <Badge variant={item.status === '사용' ? 'default' : 'secondary'}>
                {item.status}
              </Badge>
            </TableCell>
            <TableCell className="text-center">{item.author}</TableCell>
            <TableCell className="text-center">{item.changedDate}</TableCell>
          </TableRow>
        );
      },

      renderMobileCard: (
        item: PricingTable,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<PricingTable>
      ) => {
        const gp = getGradePricing(item);
        return (
          <ListMobileCard
            key={item.id}
            id={item.id}
            isSelected={handlers.isSelected}
            onToggleSelection={handlers.onToggle}
            onClick={() => handleRowClick(item)}
            headerBadges={
              <>
                <Badge variant="outline" className="text-xs">
                  {globalIndex}
                </Badge>
                <Badge variant="outline" className="text-xs font-mono">
                  {item.pricingCode}
                </Badge>
              </>
            }
            title={item.itemName}
            statusBadge={
              <Badge variant={item.status === '사용' ? 'default' : 'secondary'}>
                {item.status}
              </Badge>
            }
            infoGrid={
              <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                <InfoField label="품목코드" value={item.itemCode} />
                <InfoField label="품목유형" value={item.itemType} />
                <InfoField label="매입단가" value={formatNumber(item.purchasePrice)} />
                <InfoField label="가공비" value={formatNumber(item.processingCost)} />
                <InfoField label="마진율" value={gp ? `${gp.marginRate}%` : '-'} />
                <InfoField label="판매단가" value={gp ? formatNumber(gp.sellingPrice) : '-'} />
              </div>
            }
          />
        );
      },
    }),
    [
      handleCreate,
      handleRowClick,
      handleBulkDelete,
      startDate,
      endDate,
      searchQuery,
      selectedGrade,
      getGradePricing,
    ]
  );

  return (
    <>
      <UniversalListPage config={config} initialData={allItems} onSearchChange={setSearchQuery} />

      <DeleteConfirmDialog
        open={deleteDialogOpen}
        onOpenChange={setDeleteDialogOpen}
        description="선택한 단가표를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
        loading={isLoading}
        onConfirm={handleDeleteConfirm}
      />
    </>
  );
}
