'use client';

/**
 * 기초관리 (절곡 바라시 기초자료) — 목록 페이지
 *
 * API: GET /api/v1/bending-items (266건)
 * 패턴: IntegratedListTemplateV2 + 클라이언트 필터링
 */

import { useState, useEffect, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { useListSearchState } from '@/hooks/useListSearchState';
import { Layers, Plus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  IntegratedListTemplateV2,
  type TableColumn,
  type FilterFieldConfig,
  type FilterValues,
} from '@/components/templates/IntegratedListTemplateV2';
import { useColumnSettings } from '@/hooks/useColumnSettings';
import { ColumnSettingsPopover } from '@/components/molecules/ColumnSettingsPopover';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { toast } from 'sonner';
import { TableRow, TableCell } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import { getBendingItems, getBendingItemFilters, deleteBendingItem } from './actions';
import type { BendingItem, BendingItemFilters } from './types';

// --- 뱃지 ---

function SepBadge({ value }: { value: string }) {
  if (value === '스크린')
    return <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200 text-xs">{value}</Badge>;
  if (value === '철재')
    return <Badge variant="outline" className="bg-orange-50 text-orange-700 border-orange-200 text-xs">{value}</Badge>;
  return <span className="text-xs">{value || '-'}</span>;
}

function UABadge({ value }: { value: string }) {
  if (value === '인정')
    return <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200 text-xs">{value}</Badge>;
  if (value === '비인정')
    return <Badge variant="outline" className="bg-gray-100 text-gray-600 border-gray-300 text-xs">{value}</Badge>;
  return <span className="text-xs">{value || '-'}</span>;
}

// --- 컬럼 ---

const TABLE_COLUMNS: TableColumn[] = [
  { key: 'no', label: 'NO', className: 'text-center w-[60px]' },
  { key: 'code', label: '코드', className: 'w-[130px]', copyable: true },
  { key: 'item_sep', label: '대분류', className: 'text-center w-[70px]', copyable: true },
  { key: 'model_UA', label: '인정', className: 'text-center w-[60px]', copyable: true },
  { key: 'item_bending', label: '분류', className: 'w-[100px]', copyable: true },
  { key: 'item_name', label: '품명', className: 'w-[100px]', copyable: true },
  { key: 'item_spec', label: '규격', className: 'w-[80px]', copyable: true },
  { key: 'material', label: '재질', className: 'w-[100px]', copyable: true },
  { key: 'image_url', label: '이미지', className: 'text-center w-[80px]' },
  { key: 'model_name', label: '모델', className: 'w-[80px]', copyable: true },
  { key: 'width_sum', label: '폭합', className: 'text-right w-[60px]', copyable: true },
  { key: 'bend_count', label: '절곡수', className: 'text-center w-[60px]', copyable: true },
  { key: 'created_at', label: '등록일', className: 'w-[100px]', copyable: true },
  { key: 'modified_by', label: '수정자', className: 'w-[80px]', copyable: true },
];

const PAGE_SIZE = 30;

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

  // --- 데이터 ---
  const [items, setItems] = useState<BendingItem[]>([]);
  const [filters, setFilters] = useState<BendingItemFilters | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // --- 검색 상태 보존 ---
  const searchState = useListSearchState({
    fields: [
      { key: 'search', defaultValue: '' },
      { key: 'item_sep', defaultValue: 'all' },
      { key: 'model_UA', defaultValue: 'all' },
      { key: 'item_bending', defaultValue: 'all' },
      { key: 'material', defaultValue: 'all' },
    ],
  });

  const searchTerm = searchState.getValue('search');
  const setSearchTerm = useCallback((v: string) => searchState.setValue('search', v), [searchState]);
  const currentPage = searchState.currentPage;
  const setCurrentPage = searchState.setPage;
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());

  // --- 필터 ---
  const filterSep = searchState.getValue('item_sep');
  const filterUA = searchState.getValue('model_UA');
  const filterBending = searchState.getValue('item_bending');
  const filterMaterial = searchState.getValue('material');
  const setFilterSep = useCallback((v: string) => searchState.setValue('item_sep', v), [searchState]);
  const setFilterUA = useCallback((v: string) => searchState.setValue('model_UA', v), [searchState]);
  const setFilterBending = useCallback((v: string) => searchState.setValue('item_bending', v), [searchState]);
  const setFilterMaterial = useCallback((v: string) => searchState.setValue('material', v), [searchState]);

  // --- 삭제 ---
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);

  // --- 컬럼 설정 ---
  const {
    visibleColumns,
    allColumnsWithVisibility,
    columnWidths,
    setColumnWidth,
    toggleColumnVisibility,
    resetSettings,
    hasHiddenColumns,
  } = useColumnSettings({
    pageId: 'bending-base',
    columns: TABLE_COLUMNS,
    alwaysVisibleKeys: ['no', 'code', 'item_name'],
  });

  // --- 데이터 로드 ---
  const loadData = useCallback(async () => {
    try {
      setIsLoading(true);
      const [itemsResult, filtersResult] = await Promise.all([
        getBendingItems({ perPage: 500 }),
        getBendingItemFilters(),
      ]);

      if (itemsResult.success && itemsResult.data) {
        setItems(itemsResult.data as unknown as BendingItem[]);
      } else {
        toast.error(itemsResult.error || '기초관리 목록을 불러오는데 실패했습니다.');
      }

      if (filtersResult.success && filtersResult.data) {
        setFilters(filtersResult.data as BendingItemFilters);
      }
    } catch {
      toast.error('데이터를 불러오는 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => { loadData(); }, [loadData]);

  // --- 클라이언트 필터링 ---
  const filteredItems = useMemo(() => {
    let result = items;

    // 필터
    if (filterSep !== 'all') result = result.filter((i) => i.item_sep === filterSep);
    if (filterUA !== 'all') result = result.filter((i) => i.model_UA === filterUA);
    if (filterBending !== 'all') result = result.filter((i) => i.item_bending === filterBending);
    if (filterMaterial !== 'all') result = result.filter((i) => i.material === filterMaterial);

    // 검색
    if (searchTerm) {
      const q = searchTerm.toLowerCase();
      result = result.filter(
        (i) =>
          (i.code || '').toLowerCase().includes(q) ||
          (i.name || '').toLowerCase().includes(q) ||
          (i.item_name || '').toLowerCase().includes(q) ||
          (i.item_spec || '').toLowerCase().includes(q) ||
          (i.search_keyword || '').toLowerCase().includes(q) ||
          (i.item_bending || '').toLowerCase().includes(q)
      );
    }

    return result;
  }, [items, filterSep, filterUA, filterBending, filterMaterial, searchTerm]);

  // --- 페이지네이션 ---
  const totalPages = Math.ceil(filteredItems.length / PAGE_SIZE);
  const paginatedItems = filteredItems.slice(
    (currentPage - 1) * PAGE_SIZE,
    currentPage * PAGE_SIZE
  );

  // --- 필터 설정 ---
  const filterConfig: FilterFieldConfig[] = useMemo(() => {
    if (!filters) return [];
    return [
      {
        key: 'item_sep', label: '대분류', type: 'single' as const,
        options: (filters.item_sep || []).map((v) => ({ value: v, label: v })),
        allOptionLabel: '전체',
      },
      {
        key: 'model_UA', label: '인정', type: 'single' as const,
        options: (filters.model_UA || []).map((v) => ({ value: v, label: v })),
        allOptionLabel: '전체',
      },
      {
        key: 'item_bending', label: '분류', type: 'single' as const,
        options: (filters.item_bending || []).map((v) => ({ value: v, label: v })),
        allOptionLabel: '전체(분류)',
      },
      {
        key: 'material', label: '재질', type: 'single' as const,
        options: (filters.material || []).map((v) => ({ value: v, label: v })),
        allOptionLabel: '전체(재질)',
      },
    ];
  }, [filters]);

  const filterValues: FilterValues = useMemo(() => ({
    item_sep: filterSep,
    model_UA: filterUA,
    item_bending: filterBending,
    material: filterMaterial,
  }), [filterSep, filterUA, filterBending, filterMaterial]);

  const handleFilterChange = useCallback((key: string, value: string | string[]) => {
    const v = value as string;
    if (key === 'item_sep') setFilterSep(v);
    if (key === 'model_UA') setFilterUA(v);
    if (key === 'item_bending') setFilterBending(v);
    if (key === 'material') setFilterMaterial(v);
  }, [setFilterSep, setFilterUA, setFilterBending, setFilterMaterial]);

  const handleFilterReset = useCallback(() => {
    searchState.resetAll();
  }, [searchState]);

  // --- 삭제 ---
  const handleConfirmDelete = useCallback(async () => {
    if (!deleteTargetId) return;
    setIsDeleting(true);
    try {
      const result = await deleteBendingItem(deleteTargetId);
      if (result.success) {
        toast.success('삭제되었습니다.');
        loadData();
      } else {
        toast.error(result.error || '삭제에 실패했습니다.');
      }
    } finally {
      setIsDeleting(false);
      setIsDeleteDialogOpen(false);
      setDeleteTargetId(null);
    }
  }, [deleteTargetId, loadData]);

  // --- 선택 ---
  const toggleSelection = useCallback((id: string) => {
    setSelectedItems((prev) => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  }, []);

  const toggleSelectAll = useCallback(() => {
    setSelectedItems((prev) =>
      prev.size === paginatedItems.length
        ? new Set()
        : new Set(paginatedItems.map((i) => String(i.id)))
    );
  }, [paginatedItems]);

  // --- 테이블 행 ---
  const renderTableRow = useCallback(
    (item: BendingItem, _index: number, globalIndex: number) => {
      return (
        <TableRow
          key={item.id}
          className="cursor-pointer hover:bg-muted/50"
          onClick={() => router.push(`/production/bending/${item.id}?mode=edit`)}
        >
          <TableCell className="text-center">{globalIndex}</TableCell>
          <TableCell className="font-mono text-xs">{item.code}</TableCell>
          <TableCell className="text-center"><SepBadge value={item.item_sep} /></TableCell>
          <TableCell className="text-center"><UABadge value={item.model_UA} /></TableCell>
          <TableCell>{item.item_bending || '-'}</TableCell>
          <TableCell>{item.item_name || '-'}</TableCell>
          <TableCell>{item.item_spec || '-'}</TableCell>
          <TableCell>{item.material || '-'}</TableCell>
          <TableCell className="text-center">
            {item.image_url ? (
              <TooltipProvider delayDuration={200}>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <img src={item.image_url} alt="" className="w-10 h-10 object-contain mx-auto rounded cursor-pointer" />
                  </TooltipTrigger>
                  <TooltipContent side="left" className="p-1 max-w-none">
                    <img src={item.image_url} alt="" className="w-52 h-52 object-contain" />
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            ) : '-'}
          </TableCell>
          <TableCell>{item.model_name || '-'}</TableCell>
          <TableCell className="text-right font-mono">{item.width_sum || '-'}</TableCell>
          <TableCell className="text-center">
            {item.bend_count ? (
              <span className="text-blue-600 font-semibold">{item.bend_count}</span>
            ) : '-'}
          </TableCell>
          <TableCell>{item.created_at?.split(' ')[0] || '-'}</TableCell>
          <TableCell>{item.modified_by || '-'}</TableCell>
        </TableRow>
      );
    },
    [router]
  );

  // --- 모바일 카드 ---
  const renderMobileCard = useCallback(
    (item: BendingItem, _index: number, globalIndex: number, isSelected: boolean, onToggle: () => void) => {
      return (
        <ListMobileCard
          key={item.id}
          id={String(item.id)}
          isSelected={isSelected}
          onToggleSelection={onToggle}
          onCardClick={() => router.push(`/production/bending/${item.id}?mode=edit`)}
          headerBadges={
            <>
              <Badge variant="outline" className="bg-gray-100 text-gray-700 font-mono text-xs">
                {globalIndex}
              </Badge>
              <code className="inline-block text-xs bg-gray-100 text-gray-700 px-2.5 py-0.5 rounded-md font-mono">
                {item.code}
              </code>
            </>
          }
          title={item.item_name || item.name}
          statusBadge={<SepBadge value={item.item_sep} />}
          infoGrid={
            <div className="grid grid-cols-2 gap-x-4 gap-y-3">
              <InfoField label="분류" value={item.item_bending || '-'} />
              <InfoField label="재질" value={item.material || '-'} />
              <InfoField label="규격" value={item.item_spec || '-'} />
              <InfoField label="폭합" value={String(item.width_sum || '-')} />
            </div>
          }
        />
      );
    },
    [router]
  );

  return (
    <>
      <IntegratedListTemplateV2<BendingItem>
        title="절곡 바라시 기초자료"
        description="절곡 부품 기초 데이터 관리"
        icon={Layers}
        createButton={{
          label: '신규 등록',
          onClick: () => router.push('/production/bending?mode=new'),
        }}
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="코드/이름/품명/규격 검색..."
        filterConfig={filterConfig}
        filterValues={filterValues}
        onFilterChange={handleFilterChange}
        onFilterReset={handleFilterReset}
        filterTitle="기초관리 필터"
        tableColumns={visibleColumns}
        columnSettings={{
          columnWidths,
          onColumnResize: setColumnWidth,
          settingsPopover: (
            <ColumnSettingsPopover
              columns={allColumnsWithVisibility}
              onToggle={toggleColumnVisibility}
              onReset={resetSettings}
              hasHiddenColumns={hasHiddenColumns}
            />
          ),
        }}
        data={paginatedItems}
        selectedItems={selectedItems}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        showCheckbox={false}
        getItemId={(item) => String(item.id)}
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        pagination={{
          currentPage,
          totalPages,
          totalItems: filteredItems.length,
          itemsPerPage: PAGE_SIZE,
          onPageChange: setCurrentPage,
        }}
        isLoading={isLoading}
      />
      <DeleteConfirmDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
        onConfirm={handleConfirmDelete}
        loading={isDeleting}
        title="기초자료 삭제"
        description="해당 기초자료를 삭제하시겠습니까?"
      />
    </>
  );
}
