'use client';

/**
 * 차량일지/월간사진기록 리스트 - UniversalListPage 기반
 */

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { FileText, 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 { VehicleLog } from '../types';
import { getVehicleLogs, deleteVehicleLog, bulkDeleteVehicleLogs } from './actions';

// ===== Props 타입 =====
interface VehicleLogListProps {
  initialData: VehicleLog[];
}

export function VehicleLogList({ initialData }: VehicleLogListProps) {
  const router = useRouter();
  const deleteDialog = useDeleteDialog({
    onDelete: deleteVehicleLog,
    onBulkDelete: bulkDeleteVehicleLogs,
    onSuccess: () => window.location.reload(),
    entityName: '차량일지',
  });

  // ===== 전체 데이터 상태 =====
  const [allData, setAllData] = useState<VehicleLog[]>(initialData);

  // ===== 핸들러 =====
  const handleView = useCallback(
    (log: VehicleLog) => {
      router.push(`/vehicle-management/vehicle-log/${log.id}?mode=view`);
    },
    [router]
  );

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

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<VehicleLog> = useMemo(
    () => ({
      title: '차량일지/월간사진기록',
      description: '차량 운행 및 정비 기록을 관리합니다',
      icon: FileText,
      basePath: '/vehicle-management/vehicle-log',

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

      actions: {
        getList: async (params?: ListParams) => {
          try {
            const result = await getVehicleLogs({
              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 deleteVehicleLog(id);
          return { success: result.success, error: result.error };
        },
        deleteBulk: async (ids: string[]) => {
          const result = await bulkDeleteVehicleLogs(ids);
          return { success: result.success, error: result.error };
        },
      },

      // 레거시 컬럼 구조 (5130 기준) - 5개 컬럼
      columns: [
        { key: 'rowNumber', label: '번호', className: 'w-[60px] text-center' },
        { key: 'writeDate', label: '작성일', className: 'w-[100px]', copyable: true },
        { key: 'vehicleInfo', label: '차량종류', className: 'min-w-[180px]', copyable: true },
        { key: 'writer', label: '작성자', className: 'w-[80px]', copyable: true },
        { key: 'title', label: '글제목', className: 'min-w-[250px]', copyable: true },
      ],

      clientSideFiltering: true,
      itemsPerPage: 20,

      searchFilter: (item: VehicleLog, searchValue: string) => {
        const search = searchValue.toLowerCase();
        return (
          item.title.toLowerCase().includes(search) ||
          item.vehicleInfo.toLowerCase().includes(search) ||
          item.writer.toLowerCase().includes(search)
        );
      },

      tabs: [],

      searchPlaceholder: '제목, 차량종류, 작성자 검색...',

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

      onBulkDelete: deleteDialog.bulk.open,

      renderTableRow: (
        log: VehicleLog,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<VehicleLog>
      ) => {
        return (
          <TableRow
            key={log.id}
            className={`cursor-pointer hover:bg-muted/50 ${handlers.isSelected ? 'bg-blue-50' : ''}`}
            onClick={() => handleView(log)}
          >
            <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>{log.writeDate}</TableCell>
            <TableCell>{log.vehicleInfo}</TableCell>
            <TableCell>{log.writer}</TableCell>
            <TableCell className="font-medium">{log.title}</TableCell>
          </TableRow>
        );
      },

      renderMobileCard: (
        log: VehicleLog,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<VehicleLog>
      ) => {
        return (
          <ListMobileCard
            key={log.id}
            id={log.id}
            isSelected={handlers.isSelected}
            onToggleSelection={handlers.onToggle}
            onClick={() => handleView(log)}
            title={log.title}
            subtitle={log.vehicleInfo}
            infoGrid={
              <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                <InfoField label="작성일" value={log.writeDate} />
                <InfoField label="작성자" value={log.writer} />
              </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(log);
                    }}
                  >
                    <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(log.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((v) => v.id === deleteDialog.single.targetId)?.title || 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 VehicleLogList;
