'use client';

/**
 * 지게차 관리 리스트 - UniversalListPage 기반
 * 레거시 5130 사이트 컬럼 구조 기반
 */

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Truck, Edit, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { TableRow, TableCell } from '@/components/ui/table';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type ListParams,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import { useDeleteDialog } from '@/hooks/useDeleteDialog';
import type { Forklift } from '../types';
import { getForklifts, deleteForklift, bulkDeleteForklifts } from './actions';

interface ForkliftListProps {
  initialData: Forklift[];
}

export function ForkliftList({ initialData }: ForkliftListProps) {
  const router = useRouter();
  const deleteDialog = useDeleteDialog({
    onDelete: deleteForklift,
    onBulkDelete: bulkDeleteForklifts,
    onSuccess: () => window.location.reload(),
    entityName: '지게차',
  });

  const [allData, setAllData] = useState<Forklift[]>(initialData);

  const handleView = useCallback(
    (forklift: Forklift) => {
      router.push(`/vehicle-management/forklift/${forklift.id}?mode=view`);
    },
    [router]
  );

  const handleEdit = useCallback(
    (forklift: Forklift) => {
      router.push(`/vehicle-management/forklift/${forklift.id}?mode=edit`);
    },
    [router]
  );

  const config: UniversalListConfig<Forklift> = useMemo(
    () => ({
      title: '지게차 관리',
      description: '지게차 정보를 관리합니다',
      icon: Truck,
      basePath: '/vehicle-management/forklift',

      idField: 'id',
      getItemId: (item: Forklift) => item.id,

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

            if (result.success) {
              setAllData(result.data);
              return {
                success: true,
                data: result.data,
                totalCount: result.totalCount,
                totalPages: result.totalPages,
              };
            }
            return { success: false, error: result.error || '데이터 조회에 실패했습니다.' };
          } catch {
            return { success: false, error: '서버 오류가 발생했습니다.' };
          }
        },
        deleteItem: async (id: string) => {
          const result = await deleteForklift(id);
          return { success: result.success, error: result.error };
        },
        deleteBulk: async (ids: string[]) => {
          const result = await bulkDeleteForklifts(ids);
          return { success: result.success, error: result.error };
        },
      },

      // 레거시 컬럼 구조 (5130 기준) - 13개 컬럼
      columns: [
        { key: 'rowNumber', label: '번호', className: 'w-[50px] text-center' },
        { key: 'vehicleNumber', label: '차량번호', className: 'min-w-[100px]', copyable: true },
        { key: 'vehicleType', label: '차종', className: 'w-[90px]', copyable: true },
        { key: 'manager', label: '담당자', className: 'w-[80px]', copyable: true },
        { key: 'purchaseCompany', label: '구입업체', className: 'w-[90px]', copyable: true },
        { key: 'purchaseCompanyContact', label: '구입업체 연락처', className: 'w-[110px]', copyable: true },
        { key: 'firstRegistrationDate', label: '최초등록일', className: 'w-[90px]', copyable: true },
        { key: 'purchaseDate', label: '구매일자', className: 'w-[90px]', copyable: true },
        { key: 'purchaseType', label: '구매 유형', className: 'w-[80px]', copyable: true },
        { key: 'partsChangeCycle', label: '부속품 교환 주기', className: 'w-[100px]', copyable: true },
        { key: 'partsChangeRecords', label: '부속품 교환일', className: 'min-w-[150px]', copyable: true },
        { key: 'maintenanceRecords', label: '정비 정보', className: 'min-w-[150px]', copyable: true },
        { key: 'remarks', label: '비고', className: 'min-w-[150px]', copyable: true },
      ],

      clientSideFiltering: true,
      itemsPerPage: 20,

      searchFilter: (item: Forklift, searchValue: string) => {
        const search = searchValue.toLowerCase();
        return (
          item.vehicleNumber.toLowerCase().includes(search) ||
          item.vehicleType.toLowerCase().includes(search) ||
          item.managerMain.toLowerCase().includes(search) ||
          item.managerSub.toLowerCase().includes(search) ||
          item.purchaseCompany.toLowerCase().includes(search)
        );
      },

      tabs: [],
      searchPlaceholder: '지게차번호, 차종, 담당자, 구입업체 검색...',

      headerActions: () => (
        <Button
          className="ml-auto"
          onClick={() => router.push('/vehicle-management/forklift/new?mode=new')}
        >
          <Truck className="w-4 h-4 mr-2" />
          지게차 등록
        </Button>
      ),

      onBulkDelete: deleteDialog.bulk.open,

      renderTableRow: (
        forklift: Forklift,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Forklift>
      ) => {
        // 부속품 교환일 포맷
        const partsChangeText = forklift.partsChangeRecords?.length > 0
          ? forklift.partsChangeRecords.map(r =>
              `${r.date}, 주행거리 : ${r.mileage || ''} km`
            ).join('\n')
          : '정보 없음';

        // 정비내역 포맷
        const maintenanceText = forklift.maintenanceRecords?.length > 0
          ? forklift.maintenanceRecords.map(r =>
              `${r.date}: ${r.description}`
            ).join('\n')
          : '정보 없음';

        // 담당자 (정/부 합침)
        const managerText = [forklift.managerMain, forklift.managerSub]
          .filter(Boolean)
          .join(' / ') || '-';

        return (
          <TableRow
            key={forklift.id}
            className={`cursor-pointer hover:bg-muted/50 ${handlers.isSelected ? 'bg-blue-50' : ''}`}
            onClick={() => handleView(forklift)}
          >
            <TableCell onClick={(e) => e.stopPropagation()} className="text-center">
              <Checkbox
                checked={handlers.isSelected}
                onCheckedChange={handlers.onToggle}
              />
            </TableCell>
            <TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
            <TableCell className="font-medium">{forklift.vehicleNumber}</TableCell>
            <TableCell>{forklift.vehicleType}</TableCell>
            <TableCell>{managerText}</TableCell>
            <TableCell>{forklift.purchaseCompany || '-'}</TableCell>
            <TableCell>{forklift.purchaseCompanyContact || '-'}</TableCell>
            <TableCell>{forklift.firstRegistrationDate || '-'}</TableCell>
            <TableCell>{forklift.purchaseDate || '-'}</TableCell>
            <TableCell>{forklift.purchaseType || '-'}</TableCell>
            <TableCell>{forklift.partsChangeCycle || '정보 없음'}</TableCell>
            <TableCell className="whitespace-pre-line text-xs">{partsChangeText}</TableCell>
            <TableCell className="whitespace-pre-line text-xs">{maintenanceText}</TableCell>
            <TableCell className="whitespace-pre-line text-xs">{forklift.remarks || '-'}</TableCell>
          </TableRow>
        );
      },

      renderMobileCard: (
        forklift: Forklift,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Forklift>
      ) => {
        // 담당자 (정/부 합침)
        const managerText = [forklift.managerMain, forklift.managerSub]
          .filter(Boolean)
          .join(' / ') || '-';

        // 부속품 교환일 포맷
        const partsChangeText = forklift.partsChangeRecords?.length > 0
          ? forklift.partsChangeRecords.map(r => `${r.date}`).join(', ')
          : '정보 없음';

        // 정비내역 포맷
        const maintenanceText = forklift.maintenanceRecords?.length > 0
          ? forklift.maintenanceRecords.map(r => `${r.date}: ${r.description}`).join('\n')
          : '정보 없음';

        return (
          <ListMobileCard
            key={forklift.id}
            id={forklift.id}
            isSelected={handlers.isSelected}
            onToggleSelection={handlers.onToggle}
            onClick={() => handleView(forklift)}
            title={forklift.vehicleNumber}
            subtitle={`${forklift.vehicleType} (${forklift.purchaseType || '-'})`}
            infoGrid={
              <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                <InfoField label="차종" value={forklift.vehicleType} />
                <InfoField label="담당자" value={managerText} />
                <InfoField label="구입업체" value={forklift.purchaseCompany || '-'} />
                <InfoField label="구입업체 연락처" value={forklift.purchaseCompanyContact || '-'} />
                <InfoField label="최초등록일" value={forklift.firstRegistrationDate || '-'} />
                <InfoField label="구매일자" value={forklift.purchaseDate || '-'} />
                <InfoField label="구매 유형" value={forklift.purchaseType || '-'} />
                <InfoField label="부속품 교환 주기" value={forklift.partsChangeCycle || '정보 없음'} />
                <InfoField label="부속품 교환일" value={partsChangeText} className="col-span-2" />
                <InfoField label="정비 정보" value={maintenanceText} className="col-span-2 whitespace-pre-line" />
                {forklift.remarks && (
                  <InfoField label="비고" value={forklift.remarks} className="col-span-2" />
                )}
              </div>
            }
            actions={
              handlers.isSelected ? (
                <div className="flex gap-2 flex-wrap">
                  <Button
                    variant="default"
                    size="default"
                    className="flex-1 min-w-[100px] h-11"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleEdit(forklift);
                    }}
                  >
                    <Edit className="h-4 w-4 mr-2" />
                    수정
                  </Button>
                  <Button
                    variant="outline"
                    size="default"
                    className="flex-1 min-w-[100px] h-11 border-red-200 text-red-600 hover:border-red-300 bg-transparent"
                    onClick={(e) => {
                      e.stopPropagation();
                      deleteDialog.single.open(forklift.id);
                    }}
                    disabled={deleteDialog.isPending}
                  >
                    <Trash2 className="h-4 w-4 mr-2" />
                    삭제
                  </Button>
                </div>
              ) : undefined
            }
          />
        );
      },
    }),
    [router, handleView, handleEdit, deleteDialog]
  );

  return (
    <>
      <UniversalListPage config={config} initialData={initialData} />

      <DeleteConfirmDialog
        open={deleteDialog.single.isOpen}
        onOpenChange={deleteDialog.single.onOpenChange}
        description={
          <>
            {deleteDialog.single.targetId
              ? `차량번호: ${allData.find((f) => f.id === deleteDialog.single.targetId)?.vehicleNumber || deleteDialog.single.targetId}`
              : ''}
            <br />
            이 지게차를 삭제하시겠습니까?
          </>
        }
        loading={deleteDialog.isPending}
        onConfirm={deleteDialog.single.confirm}
      />

      <DeleteConfirmDialog
        open={deleteDialog.bulk.isOpen}
        onOpenChange={deleteDialog.bulk.onOpenChange}
        description={`선택한 ${deleteDialog.bulk.ids.length}개의 지게차를 삭제하시겠습니까?`}
        loading={deleteDialog.isPending}
        onConfirm={deleteDialog.bulk.confirm}
      />
    </>
  );
}

export default ForkliftList;
