'use client';

/**
 * 배차차량 목록 페이지
 *
 * - DateRangeSelector
 * - 통계 카드 3개: 선불, 착불, 합계
 * - 상태 필터: 전체/작성대기/작성완료
 * - 테이블 18컬럼
 */

import { useState, useEffect, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
  Truck,
  CreditCard,
  Banknote,
  Calculator,
  Eye,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { TableCell, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type StatCard,
  type ListParams,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { getVehicleDispatches, getVehicleDispatchStats } from './actions';
import {
  VEHICLE_DISPATCH_STATUS_LABELS,
  VEHICLE_DISPATCH_STATUS_STYLES,
  FREIGHT_COST_LABELS,
  FREIGHT_COST_STYLES,
} from './types';
import type { VehicleDispatchItem, VehicleDispatchStats } from './types';
import { formatNumber as formatAmount } from '@/lib/utils/amount';
import { getLocalDateString } from '@/lib/utils/date';

const ITEMS_PER_PAGE = 20;

export function VehicleDispatchList() {
  const router = useRouter();

  // ===== 통계 =====
  const [dispatchStats, setDispatchStats] = useState<VehicleDispatchStats | null>(null);

  // ===== 날짜 범위 =====
  const today = new Date();
  const [startDate, setStartDate] = useState(() => {
    const d = new Date(today.getFullYear(), today.getMonth(), 1);
    return getLocalDateString(d);
  });
  const [endDate, setEndDate] = useState(() => {
    const d = new Date(today.getFullYear(), today.getMonth() + 1, 0);
    return getLocalDateString(d);
  });

  // 초기 통계 로드
  useEffect(() => {
    const loadStats = async () => {
      try {
        const result = await getVehicleDispatchStats();
        if (result.success && result.data) {
          setDispatchStats(result.data);
        }
      } catch (error) {
        console.error('[VehicleDispatchList] loadStats error:', error);
      }
    };
    loadStats();
  }, []);

  // ===== 행 클릭 핸들러 =====
  const handleRowClick = useCallback(
    (item: VehicleDispatchItem) => {
      router.push(`/ko/outbound/vehicle-dispatches/${item.id}?mode=view`);
    },
    [router]
  );

  // ===== 통계 카드 (3개: 선불, 착불, 합계) =====
  const stats: StatCard[] = useMemo(
    () => [
      {
        label: '선불',
        value: `${formatAmount(dispatchStats?.prepaidAmount || 0)}원`,
        icon: CreditCard,
        iconColor: 'text-blue-600',
      },
      {
        label: '착불',
        value: `${formatAmount(dispatchStats?.collectAmount || 0)}원`,
        icon: Banknote,
        iconColor: 'text-orange-600',
      },
      {
        label: '합계',
        value: `${formatAmount(dispatchStats?.totalAmount || 0)}원`,
        icon: Calculator,
        iconColor: 'text-green-600',
      },
    ],
    [dispatchStats]
  );

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<VehicleDispatchItem> = useMemo(
    () => ({
      title: '배차차량 목록',
      description: '배차차량을 관리합니다',
      icon: Truck,
      basePath: '/outbound/vehicle-dispatches',

      idField: 'id',

      actions: {
        getList: async (params?: ListParams) => {
          try {
            const result = await getVehicleDispatches({
              page: params?.page || 1,
              perPage: params?.pageSize || ITEMS_PER_PAGE,
              search: params?.search || undefined,
            });

            if (result.success) {
              // 통계 다시 로드
              const statsResult = await getVehicleDispatchStats();
              if (statsResult.success && statsResult.data) {
                setDispatchStats(statsResult.data);
              }

              return {
                success: true,
                data: result.data,
                totalCount: result.pagination.total,
                totalPages: result.pagination.lastPage,
              };
            }
            return { success: false, error: result.error };
          } catch (error) {
            console.error('[VehicleDispatchList] getList error:', error);
            return { success: false, error: '데이터 로드 중 오류가 발생했습니다.' };
          }
        },
      },

      // 날짜 범위 선택기
      dateRangeSelector: {
        enabled: true,
        showPresets: true,
        startDate,
        endDate,
        onStartDateChange: setStartDate,
        onEndDateChange: setEndDate,
      },

      // 테이블 컬럼 (13개)
      columns: [
        { key: 'no', label: 'No.', className: 'w-[50px] text-center' },
        { key: 'dispatchNo', label: '배차번호', className: 'min-w-[130px]', copyable: true },
        { key: 'lotNo', label: '로트번호', className: 'min-w-[120px]', copyable: true },
        { key: 'siteName', label: '현장명', className: 'min-w-[100px]', copyable: true },
        { key: 'orderCustomer', label: '수주처', className: 'min-w-[100px]', copyable: true },
        { key: 'logisticsCompany', label: '물류업체', className: 'min-w-[90px]', copyable: true },
        { key: 'supplyAmount', label: '공급가액', className: 'w-[100px] text-right', copyable: true },
        { key: 'vat', label: '부가세', className: 'w-[90px] text-right', copyable: true },
        { key: 'totalAmount', label: '합계', className: 'w-[100px] text-right', copyable: true },
        { key: 'freightCostType', label: '선/착불', className: 'w-[70px] text-center', copyable: true },
        { key: 'writer', label: '작성자', className: 'w-[80px] text-center', copyable: true },
        { key: 'status', label: '상태', className: 'w-[80px] text-center' },
        { key: 'remarks', label: '비고', className: 'min-w-[100px]', copyable: true },
      ],

      // 상태 필터
      filterConfig: [{
        key: 'status',
        label: '상태',
        type: 'single' as const,
        options: [
          { value: 'draft', label: '작성대기' },
          { value: 'completed', label: '작성완료' },
        ],
        allOptionLabel: '전체',
      }],

      // 서버 사이드 페이지네이션
      clientSideFiltering: false,
      itemsPerPage: ITEMS_PER_PAGE,

      // 검색
      searchPlaceholder: '배차번호, 로트번호, 현장명, 수주처 검색...',
      searchFilter: (item: VehicleDispatchItem, search: string) => {
        const s = search.toLowerCase();
        return (
          item.dispatchNo.toLowerCase().includes(s) ||
          (item.lotNo || item.shipmentNo).toLowerCase().includes(s) ||
          item.siteName.toLowerCase().includes(s) ||
          item.orderCustomer.toLowerCase().includes(s)
        );
      },

      // 통계 카드
      stats,

      // 테이블 행 렌더링
      renderTableRow: (
        item: VehicleDispatchItem,
        _index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<VehicleDispatchItem>
      ) => {
        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="w-[50px] text-center text-muted-foreground">{globalIndex}</TableCell>
            <TableCell className="min-w-[130px] font-medium">{item.dispatchNo}</TableCell>
            <TableCell className="min-w-[120px]">{item.lotNo || item.shipmentNo}</TableCell>
            <TableCell className="min-w-[100px] truncate">{item.siteName}</TableCell>
            <TableCell className="min-w-[100px]">{item.orderCustomer}</TableCell>
            <TableCell className="min-w-[90px]">{item.logisticsCompany}</TableCell>
            <TableCell className="w-[100px] text-right">{formatAmount(item.supplyAmount || 0)}</TableCell>
            <TableCell className="w-[90px] text-right">{formatAmount(item.vat || 0)}</TableCell>
            <TableCell className="w-[100px] text-right font-medium">{formatAmount(item.totalAmount || 0)}</TableCell>
            <TableCell className="w-[70px] text-center">
              {item.freightCostType ? (
                <Badge className={`text-xs ${FREIGHT_COST_STYLES[item.freightCostType]}`}>
                  {FREIGHT_COST_LABELS[item.freightCostType]}
                </Badge>
              ) : '-'}
            </TableCell>
            <TableCell className="w-[80px] text-center">{item.writer || '-'}</TableCell>
            <TableCell className="w-[80px] text-center">
              <Badge className={`text-xs ${VEHICLE_DISPATCH_STATUS_STYLES[item.status]}`}>
                {VEHICLE_DISPATCH_STATUS_LABELS[item.status]}
              </Badge>
            </TableCell>
            <TableCell className="min-w-[100px] truncate">{item.remarks || '-'}</TableCell>
          </TableRow>
        );
      },

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: VehicleDispatchItem,
        _index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<VehicleDispatchItem>
      ) => {
        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">
                  {item.dispatchNo}
                </Badge>
              </>
            }
            title={item.siteName}
            statusBadge={
              <Badge className={`text-xs ${VEHICLE_DISPATCH_STATUS_STYLES[item.status]}`}>
                {VEHICLE_DISPATCH_STATUS_LABELS[item.status]}
              </Badge>
            }
            infoGrid={
              <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                <InfoField label="로트번호" value={item.lotNo || item.shipmentNo} />
                <InfoField label="수주처" value={item.orderCustomer} />
                <InfoField label="물류업체" value={item.logisticsCompany} />
                <InfoField label="공급가액" value={`${formatAmount(item.supplyAmount)}원`} />
                <InfoField label="합계" value={`${formatAmount(item.totalAmount)}원`} />
                <InfoField
                  label="선/착불"
                  value={FREIGHT_COST_LABELS[item.freightCostType]}
                />
                <InfoField label="작성자" value={item.writer} />
              </div>
            }
            actions={
              handlers.isSelected && (
                <div className="flex items-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    className="flex-1"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleRowClick(item);
                    }}
                  >
                    <Eye className="w-4 h-4 mr-1" />
                    상세
                  </Button>
                </div>
              )
            }
          />
        );
      },
    }),
    [stats, startDate, endDate, handleRowClick]
  );

  return <UniversalListPage config={config} />;
}
