'use client';

/**
 * 수리이력 목록 페이지
 */

import { useState, useEffect, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
  Wrench,
  Plus,
  Trash2,
} from 'lucide-react';
import { toast } from 'sonner';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { TableCell, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type ListParams,
  type FilterFieldConfig,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import {
  getRepairList,
  deleteRepair,
  getEquipmentOptions,
} from '@/components/quality/EquipmentManagement/actions';
import type {
  EquipmentRepair,
  EquipmentOptions,
} from '@/components/quality/EquipmentManagement/types';
import {
  REPAIR_TYPE_LABEL,
  REPAIR_TYPE_COLOR,
} from '@/components/quality/EquipmentManagement/types';

const ITEMS_PER_PAGE = 20;

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

  const [dateFrom, setDateFrom] = useState<string>('');
  const [dateTo, setDateTo] = useState<string>('');
  const [options, setOptions] = useState<EquipmentOptions | null>(null);

  const [deleteTarget, setDeleteTarget] = useState<EquipmentRepair | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);

  useEffect(() => {
    getEquipmentOptions().then((result) => {
      if (result.success && result.data) {
        setOptions(result.data);
      }
    });
  }, []);

  // ===== filterConfig (공용 모바일 필터 지원) =====
  const filterConfig: FilterFieldConfig[] = useMemo(() => [
    {
      key: 'equipmentId',
      label: '설비',
      type: 'single' as const,
      options: (options?.equipmentList || []).map((eq) => ({
        value: String(eq.id),
        label: `${eq.equipmentCode} ${eq.name}`,
      })),
      allOptionLabel: '설비 전체',
    },
    {
      key: 'repairType',
      label: '보전구분',
      type: 'single' as const,
      options: [
        { value: 'internal', label: '사내' },
        { value: 'external', label: '외주' },
      ],
      allOptionLabel: '구분 전체',
    },
  ], [options]);

  const handleDeleteClick = useCallback((e: React.MouseEvent, item: EquipmentRepair) => {
    e.stopPropagation();
    setDeleteTarget(item);
  }, []);

  const handleDeleteConfirm = useCallback(async () => {
    if (!deleteTarget) return;
    setIsDeleting(true);
    try {
      const result = await deleteRepair(deleteTarget.id);
      if (result.success) {
        toast.success('수리이력이 삭제되었습니다.');
        setRefreshKey((prev) => prev + 1);
      } else {
        toast.error(result.error || '삭제에 실패했습니다.');
      }
    } finally {
      setIsDeleting(false);
      setDeleteTarget(null);
    }
  }, [deleteTarget]);

  const config: UniversalListConfig<EquipmentRepair> = useMemo(
    () => ({
      title: '수리이력',
      description: '설비 수리이력을 관리합니다',
      icon: Wrench,
      basePath: '/quality/equipment-repairs',
      idField: 'id',

      actions: {
        getList: async (params?: ListParams) => {
          const filters = params?.filters || {};
          const result = await getRepairList({
            page: params?.page || 1,
            perPage: params?.pageSize || ITEMS_PER_PAGE,
            search: params?.search || undefined,
            equipmentId: (filters.equipmentId as string) || undefined,
            repairType: (filters.repairType as string) || undefined,
            dateFrom: dateFrom || undefined,
            dateTo: dateTo || undefined,
          });

          if (result.success) {
            return {
              success: true,
              data: result.data,
              totalCount: result.pagination.total,
              totalPages: result.pagination.lastPage,
            };
          }
          return { success: false, error: result.error };
        },
      },

      headerActions: () => (
        <Button
          size="sm"
          onClick={() => router.push('/quality/equipment-repairs?mode=new')}
        >
          <Plus className="h-4 w-4 mr-1" />
          수리이력 등록
        </Button>
      ),

      // 필터 (공용 MobileFilter 연동)
      filterConfig,
      filterTitle: '수리이력 필터',

      // 날짜 범위 선택기
      dateRangeSelector: {
        enabled: true,
        startDate: dateFrom,
        endDate: dateTo,
        onStartDateChange: setDateFrom,
        onEndDateChange: setDateTo,
        presets: ['thisMonth', 'lastMonth', 'twoMonthsAgo'] as import('@/components/molecules/DateRangeSelector').DatePreset[],
      },

      columns: [
        { key: 'repairDate', label: '수리일', className: 'w-[110px] text-center' },
        { key: 'equipment', label: '설비', className: 'min-w-[180px]' },
        { key: 'repairType', label: '보전구분', className: 'w-[80px] text-center' },
        { key: 'repairHours', label: '수리시간', className: 'w-[80px] text-center' },
        { key: 'description', label: '수리내용', className: 'min-w-[250px]' },
        { key: 'cost', label: '비용', className: 'w-[110px] text-right' },
        { key: 'vendor', label: '외주업체', className: 'w-[100px]' },
        { key: 'actions', label: '액션', className: 'w-[60px] text-center' },
      ],

      clientSideFiltering: false,
      itemsPerPage: ITEMS_PER_PAGE,
      hideSearch: false,
      searchPlaceholder: '설비명/수리내용 검색...',

      renderTableRow: (
        item: EquipmentRepair,
        _index: number,
        _globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<EquipmentRepair>
      ) => (
        <TableRow key={item.id} className="hover:bg-muted/50">
          <TableCell className="text-center">
            <Checkbox
              checked={handlers.isSelected}
              onCheckedChange={() => handlers.onToggle()}
              onClick={(e) => e.stopPropagation()}
            />
          </TableCell>
          <TableCell className="text-center">{item.repairDate}</TableCell>
          <TableCell>
            <span className="font-medium text-blue-600">{item.equipmentCode}</span>
            {' '}{item.equipmentName}
          </TableCell>
          <TableCell className="text-center">
            {item.repairType ? (
              <Badge className={REPAIR_TYPE_COLOR[item.repairType]} variant="secondary">
                {REPAIR_TYPE_LABEL[item.repairType]}
              </Badge>
            ) : '-'}
          </TableCell>
          <TableCell className="text-center">{item.repairHours ? `${item.repairHours}h` : '-'}</TableCell>
          <TableCell className="truncate max-w-[250px]">{item.description || '-'}</TableCell>
          <TableCell className="text-right">{item.cost ? `${Number(item.cost).toLocaleString()}원` : '-'}</TableCell>
          <TableCell>{item.vendor || '-'}</TableCell>
          <TableCell className="text-center">
            <Button
              variant="ghost"
              size="sm"
              className="h-7 px-2 text-red-600 hover:text-red-800"
              onClick={(e) => handleDeleteClick(e, item)}
            >
              삭제
            </Button>
          </TableCell>
        </TableRow>
      ),

      renderMobileCard: (
        item: EquipmentRepair,
        _index: number,
        _globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<EquipmentRepair>
      ) => (
        <ListMobileCard
          key={item.id}
          title={`${item.equipmentCode} ${item.equipmentName}`}
          headerBadges={
            item.repairType ? (
              <Badge className={REPAIR_TYPE_COLOR[item.repairType]} variant="secondary">
                {REPAIR_TYPE_LABEL[item.repairType]}
              </Badge>
            ) : undefined
          }
          infoGrid={
            <div className="grid grid-cols-1 gap-1">
              <InfoField label="수리일" value={item.repairDate} />
              <InfoField label="비용" value={item.cost ? `${Number(item.cost).toLocaleString()}원` : '-'} />
              <InfoField label="수리시간" value={item.repairHours ? `${item.repairHours}h` : '-'} />
              <InfoField label="외주업체" value={item.vendor || '-'} />
            </div>
          }
          showCheckbox
          isSelected={handlers.isSelected}
          onToggleSelection={() => handlers.onToggle()}
          actions={[
            {
              label: '삭제',
              icon: Trash2,
              variant: 'destructive' as const,
              onClick: () => setDeleteTarget(item),
            },
          ]}
        />
      ),
    }),
    [filterConfig, dateFrom, dateTo, handleDeleteClick, router]
  );

  return (
    <>
      <UniversalListPage
        key={`${refreshKey}-${dateFrom}-${dateTo}`}
        config={config}
      />

      <DeleteConfirmDialog
        open={!!deleteTarget}
        onOpenChange={(open: boolean) => !open && setDeleteTarget(null)}
        itemName={deleteTarget ? `${deleteTarget.equipmentCode} ${deleteTarget.repairDate}` : undefined}
        description={`"${deleteTarget?.equipmentCode} ${deleteTarget?.repairDate}" 수리이력을 삭제하시겠습니까?`}
        loading={isDeleting}
        onConfirm={handleDeleteConfirm}
      />
    </>
  );
}
