'use client';

/**
 * 설비 등록대장 - 목록 페이지
 *
 * 필터: 검색(설비번호/설비명), 상태, 라인, 유형
 * 테이블: 설비번호, 설비명, 유형, 위치, 생산라인, 상태, 관리자 정/부, QR, 액션
 * 액션: 엑셀 Import, 설비 등록
 */

import { useState, useEffect, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
  Wrench,
  Plus,
  FileUp,
  SquarePen,
  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 {
  getEquipmentList,
  getEquipmentOptions,
  deleteEquipment,
} from './actions';
import type { Equipment, EquipmentOptions, EquipmentStatus } from './types';
import {
  EQUIPMENT_STATUS_LABEL,
  EQUIPMENT_STATUS_COLOR,
} from './types';

const ITEMS_PER_PAGE = 20;

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

  // ===== 필터 옵션 (동적) =====
  const [options, setOptions] = useState<EquipmentOptions | null>(null);

  // ===== 삭제 확인 =====
  const [deleteTarget, setDeleteTarget] = useState<Equipment | 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: 'status',
      label: '상태',
      type: 'single' as const,
      options: [
        { value: 'active', label: '가동' },
        { value: 'idle', label: '유휴' },
        { value: 'disposed', label: '폐기' },
      ],
      allOptionLabel: '상태 전체',
    },
    {
      key: 'productionLine',
      label: '라인',
      type: 'single' as const,
      options: (options?.productionLines || []).map((line) => ({
        value: line,
        label: line,
      })),
      allOptionLabel: '라인 전체',
    },
    {
      key: 'equipmentType',
      label: '유형',
      type: 'single' as const,
      options: (options?.equipmentTypes || []).map((type) => ({
        value: type,
        label: type,
      })),
      allOptionLabel: '유형 전체',
    },
  ], [options]);

  // ===== 행 클릭 =====
  const handleRowClick = useCallback(
    (item: Equipment) => {
      router.push(`/quality/equipment/${item.id}`);
    },
    [router]
  );

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

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

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<Equipment> = useMemo(
    () => ({
      title: '설비 등록대장',
      description: '설비 정보를 관리합니다',
      icon: Wrench,
      basePath: '/quality/equipment',
      idField: 'id',

      // API 액션
      actions: {
        getList: async (params?: ListParams) => {
          const filters = params?.filters || {};
          const result = await getEquipmentList({
            page: params?.page || 1,
            perPage: params?.pageSize || ITEMS_PER_PAGE,
            search: params?.search || undefined,
            status: (filters.status as EquipmentStatus) || undefined,
            productionLine: (filters.productionLine as string) || undefined,
            equipmentType: (filters.equipmentType as string) || 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: () => (
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => router.push('/quality/equipment/import')}
          >
            <FileUp className="h-4 w-4 mr-1" />
            엑셀 Import
          </Button>
          <Button
            size="sm"
            onClick={() => router.push('/quality/equipment?mode=new')}
          >
            <Plus className="h-4 w-4 mr-1" />
            설비 등록
          </Button>
        </div>
      ),

      // 필터 (공용 MobileFilter 연동)
      filterConfig,
      filterTitle: '설비 필터',

      // 테이블 컬럼
      columns: [
        { key: 'no', label: 'No.', className: 'w-[50px] text-center' },
        { key: 'equipmentCode', label: '설비번호', className: 'min-w-[110px]', copyable: true },
        { key: 'name', label: '설비명', className: 'min-w-[100px]', copyable: true },
        { key: 'equipmentType', label: '유형', className: 'w-[80px] text-center' },
        { key: 'location', label: '위치', className: 'w-[80px] text-center' },
        { key: 'productionLine', label: '생산라인', className: 'w-[80px] text-center' },
        { key: 'status', label: '상태', className: 'w-[70px] text-center' },
        { key: 'managerName', label: '관리자 정', className: 'w-[80px] text-center' },
        { key: 'subManagerName', label: '관리자 부', className: 'w-[80px] text-center' },
        { key: 'purchaseDate', label: '구입일', className: 'w-[100px] text-center' },
        { key: 'qr', label: 'QR', className: 'w-[60px] text-center' },
        { key: 'actions', label: '액션', className: 'w-[100px] text-center' },
      ],

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

      // 검색 + 필터 (hideSearch: false → 검색 카드 안에 extraFilters 표시)
      hideSearch: false,
      searchPlaceholder: '설비번호/설비명 검색...',

      // 테이블 행 렌더링
      renderTableRow: (
        item: Equipment,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Equipment>
      ) => (
        <TableRow
          key={item.id}
          className="cursor-pointer hover:bg-muted/50"
          onClick={() => handlers.onRowClick?.()}
        >
          <TableCell className="text-center">
            <Checkbox
              checked={handlers.isSelected}
              onCheckedChange={() => handlers.onToggle()}
              onClick={(e) => e.stopPropagation()}
            />
          </TableCell>
          <TableCell className="text-center">{globalIndex}</TableCell>
          <TableCell className="font-medium text-blue-600">{item.equipmentCode}</TableCell>
          <TableCell>{item.name}</TableCell>
          <TableCell className="text-center">{item.equipmentType || '-'}</TableCell>
          <TableCell className="text-center">{item.location || '-'}</TableCell>
          <TableCell className="text-center">{item.productionLine || '-'}</TableCell>
          <TableCell className="text-center">
            <Badge className={EQUIPMENT_STATUS_COLOR[item.status] || ''} variant="secondary">
              {EQUIPMENT_STATUS_LABEL[item.status] || item.status}
            </Badge>
          </TableCell>
          <TableCell className="text-center">{item.managerName || '-'}</TableCell>
          <TableCell className="text-center">{item.subManagerName || '-'}</TableCell>
          <TableCell className="text-center">{item.purchaseDate || '-'}</TableCell>
          <TableCell className="text-center">-</TableCell>
          <TableCell className="text-center">
            <div className="flex items-center justify-center gap-1">
              <Button
                variant="ghost"
                size="sm"
                className="h-7 px-2 text-blue-600 hover:text-blue-800"
                onClick={(e) => {
                  e.stopPropagation();
                  router.push(`/quality/equipment/${item.id}?mode=edit`);
                }}
              >
                수정
              </Button>
              <Button
                variant="ghost"
                size="sm"
                className="h-7 px-2 text-red-600 hover:text-red-800"
                onClick={(e) => handleDeleteClick(e, item)}
              >
                삭제
              </Button>
            </div>
          </TableCell>
        </TableRow>
      ),

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: Equipment,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Equipment>
      ) => (
        <ListMobileCard
          key={item.id}
          title={`${item.equipmentCode} ${item.name}`}
          headerBadges={
            <Badge className={EQUIPMENT_STATUS_COLOR[item.status]} variant="secondary">
              {EQUIPMENT_STATUS_LABEL[item.status]}
            </Badge>
          }
          infoGrid={
            <div className="grid grid-cols-2 gap-2">
              <InfoField label="유형" value={item.equipmentType || '-'} />
              <InfoField label="위치" value={item.location || '-'} />
              <InfoField label="생산라인" value={item.productionLine || '-'} />
              <InfoField label="관리자" value={item.managerName || '-'} />
            </div>
          }
          showCheckbox
          isSelected={handlers.isSelected}
          onToggleSelection={() => handlers.onToggle()}
          onClick={() => handlers.onRowClick?.()}
          actions={[
            {
              label: '수정',
              icon: SquarePen,
              onClick: () => router.push(`/quality/equipment/${item.id}?mode=edit`),
            },
            {
              label: '삭제',
              icon: Trash2,
              variant: 'destructive' as const,
              onClick: () => setDeleteTarget(item),
            },
          ]}
        />
      ),

      // 행 클릭
      onRowClick: handleRowClick,
    }),
    [filterConfig, handleRowClick, handleDeleteClick, router]
  );

  return (
    <>
      <UniversalListPage
        key={refreshKey}
        config={config}
      />

      <DeleteConfirmDialog
        open={!!deleteTarget}
        onOpenChange={(open: boolean) => !open && setDeleteTarget(null)}
        itemName={deleteTarget?.name}
        description={`"${deleteTarget?.name}" 설비를 삭제하시겠습니까?`}
        loading={isDeleting}
        onConfirm={handleDeleteConfirm}
      />
    </>
  );
}
