'use client';

/**
 * 부적합관리 - 목록 페이지
 *
 * UniversalListPage 기반
 * - 상단 통계 카드 (접수/분석중/조치완료/종결)
 * - 필터: 상태, 유형 (filterConfig), 날짜범위
 * - 테이블: 체크박스, No, 부적합번호, 유형, 현장명, 품목명, 발생일, 비용합계, 상태, 등록자
 */

import { useState, useEffect, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import {
  AlertTriangle,
  Search,
  Clock,
  CheckCircle2,
  Lock,
  Eye,
  Edit,
  Trash2,
  Loader2,
  Plus,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { BadgeSm } from '@/components/atoms/BadgeSm';
import {
  UniversalListPage,
  type UniversalListConfig,
  type TableColumn,
  type FilterFieldConfig,
} from '@/components/templates/UniversalListPage';
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 { formatAmount } from '@/lib/utils/amount';
import {
  getNonconformingReports,
  getNonconformingStats,
  deleteNonconformingReport,
} from './actions';
import {
  NC_STATUS_CONFIG,
  NC_TYPE_LABELS,
  NC_STATUS_OPTIONS,
  NC_TYPE_OPTIONS,
  type NonconformingListItem,
  type NonconformingStats,
  type NcStatus,
  type NcType,
} from './types';

const BASE_PATH = '/material/nonconforming-management';

function getStatusBadge(status: NcStatus) {
  const config = NC_STATUS_CONFIG[status];
  return <BadgeSm className={config.className}>{config.label}</BadgeSm>;
}

export function NonconformingList() {
  const router = useRouter();
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  // 날짜 범위
  const [startDate, setStartDate] = useState<string>('');
  const [endDate, setEndDate] = useState<string>('');

  // 필터 상태
  const [filterValues, setFilterValues] = useState<Record<string, string | string[]>>({
    status: 'all',
    nc_type: 'all',
  });

  const filterConfig: FilterFieldConfig[] = [
    {
      key: 'status',
      label: '상태',
      type: 'single',
      options: NC_STATUS_OPTIONS.map((o) => ({ value: o.value, label: o.label })),
      allOptionLabel: '전체 상태',
    },
    {
      key: 'nc_type',
      label: '유형',
      type: 'single',
      options: NC_TYPE_OPTIONS.map((o) => ({ value: o.value, label: o.label })),
      allOptionLabel: '전체 유형',
    },
  ];

  // 삭제 다이얼로그
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [deleteTargetIds, setDeleteTargetIds] = useState<string[]>([]);
  const [isDeleting, setIsDeleting] = useState(false);

  // API 상태
  const [data, setData] = useState<NonconformingListItem[]>([]);
  const [statsData, setStatsData] = useState<NonconformingStats | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [totalCount, setTotalCount] = useState(0);

  // 데이터 로드
  const loadData = useCallback(async () => {
    try {
      setIsLoading(true);
      const statusFilter = filterValues.status as string;
      const typeFilter = filterValues.nc_type as string;

      const [listResult, statsResult] = await Promise.all([
        getNonconformingReports({
          page: currentPage,
          per_page: itemsPerPage,
          search: searchTerm || undefined,
          status: statusFilter !== 'all' ? statusFilter : undefined,
          nc_type: typeFilter !== 'all' ? typeFilter : undefined,
          from_date: startDate || undefined,
          to_date: endDate || undefined,
        }),
        getNonconformingStats(),
      ]);

      if (listResult.success) {
        setData(listResult.data);
        setTotalCount(listResult.pagination?.total ?? 0);
      } else {
        toast.error(listResult.error || '목록 조회 실패');
      }

      if (statsResult.success && statsResult.data) {
        setStatsData(statsResult.data as NonconformingStats);
      }
    } catch {
      toast.error('데이터 로드 중 오류 발생');
    } finally {
      setIsLoading(false);
    }
  }, [currentPage, searchTerm, filterValues, startDate, endDate]);

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

  // 통계 카드
  const stats = useMemo(() => {
    const byStatus = statsData?.by_status ?? { RECEIVED: 0, ANALYZING: 0, RESOLVED: 0, CLOSED: 0 };
    return [
      { label: '접수', value: `${byStatus.RECEIVED}건`, icon: Clock, iconColor: 'text-gray-600' },
      { label: '분석중', value: `${byStatus.ANALYZING}건`, icon: Search, iconColor: 'text-yellow-600' },
      { label: '조치완료', value: `${byStatus.RESOLVED}건`, icon: CheckCircle2, iconColor: 'text-blue-600' },
      { label: '종결', value: `${byStatus.CLOSED}건`, icon: Lock, iconColor: 'text-green-600' },
    ];
  }, [statsData]);

  // 핸들러
  const handleView = (item: NonconformingListItem) => {
    router.push(`${BASE_PATH}/${item.id}`);
  };

  const handleEdit = (item: NonconformingListItem) => {
    router.push(`${BASE_PATH}/${item.id}?mode=edit`);
  };

  const handleDelete = (id: string) => {
    setDeleteTargetIds([id]);
    setIsDeleteDialogOpen(true);
  };

  const handleConfirmDelete = async () => {
    if (deleteTargetIds.length === 0) return;
    setIsDeleting(true);
    try {
      const result = await deleteNonconformingReport(deleteTargetIds[0]);
      if (result.success) {
        toast.success('삭제되었습니다.');
        setSelectedItems(new Set());
        loadData();
      } else {
        toast.error(result.error || '삭제 실패');
      }
    } catch {
      toast.error('삭제 중 오류 발생');
    } finally {
      setIsDeleting(false);
      setIsDeleteDialogOpen(false);
      setDeleteTargetIds([]);
    }
  };

  // 선택
  const toggleSelection = (id: string) => {
    const next = new Set(selectedItems);
    next.has(id) ? next.delete(id) : next.add(id);
    setSelectedItems(next);
  };

  const toggleSelectAll = () => {
    if (selectedItems.size === data.length && data.length > 0) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(data.map((d) => String(d.id))));
    }
  };

  // 테이블 컬럼
  const tableColumns: TableColumn[] = useMemo(
    () => [
      { key: 'no', label: '번호', className: 'text-center w-[60px]' },
      { key: 'nc_number', label: '부적합번호', className: 'px-2', copyable: true },
      { key: 'nc_type', label: '유형', className: 'px-2 text-center w-[90px]' },
      { key: 'site_name', label: '현장명', className: 'px-2' },
      { key: 'item_name', label: '품목명', className: 'px-2' },
      { key: 'occurred_at', label: '발생일', className: 'px-2 w-[100px]' },
      { key: 'total_cost', label: '비용합계', className: 'px-2 text-right w-[110px]' },
      { key: 'status', label: '상태', className: 'px-2 text-center w-[90px]' },
      { key: 'creator', label: '등록자', className: 'px-2 w-[80px]' },
    ],
    []
  );

  // 테이블 행
  const renderTableRow = (
    item: NonconformingListItem,
    _index: number,
    globalIndex: number,
    handlers: { isSelected: boolean; onToggle: () => void }
  ) => {
    const { isSelected, onToggle } = handlers;
    return (
      <TableRow
        key={item.id}
        className={`cursor-pointer hover:bg-muted/50 ${isSelected ? 'bg-blue-50' : ''}`}
        onClick={() => handleView(item)}
      >
        <TableCell onClick={(e) => e.stopPropagation()} className="text-center">
          <Checkbox checked={isSelected} onCheckedChange={onToggle} />
        </TableCell>
        <TableCell className="text-center">{globalIndex}</TableCell>
        <TableCell>
          <code className="text-xs bg-gray-100 text-gray-700 px-2 py-1 rounded font-mono">
            {item.nc_number}
          </code>
        </TableCell>
        <TableCell className="text-center">
          <Badge variant="outline" className="text-xs">
            {NC_TYPE_LABELS[item.nc_type] || item.nc_type}
          </Badge>
        </TableCell>
        <TableCell>{item.site_name || '-'}</TableCell>
        <TableCell>{item.item?.name || '-'}</TableCell>
        <TableCell>{item.occurred_at || '-'}</TableCell>
        <TableCell className="text-right">{formatAmount(item.total_cost)}</TableCell>
        <TableCell className="text-center">{getStatusBadge(item.status)}</TableCell>
        <TableCell>{item.creator?.name || '-'}</TableCell>
      </TableRow>
    );
  };

  // 모바일 카드
  const renderMobileCard = (
    item: NonconformingListItem,
    _index: number,
    globalIndex: number,
    handlers: { isSelected: boolean; onToggle: () => void }
  ) => {
    const { isSelected, onToggle } = handlers;
    return (
      <ListMobileCard
        key={item.id}
        id={String(item.id)}
        isSelected={isSelected}
        onToggleSelection={onToggle}
        onCardClick={() => handleView(item)}
        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 whitespace-nowrap">
              {item.nc_number}
            </code>
          </>
        }
        title={item.site_name || '(현장명 없음)'}
        statusBadge={getStatusBadge(item.status)}
        infoGrid={
          <div className="grid grid-cols-2 gap-x-4 gap-y-3">
            <InfoField label="유형" value={NC_TYPE_LABELS[item.nc_type]} />
            <InfoField label="품목명" value={item.item?.name || '-'} />
            <InfoField label="발생일" value={item.occurred_at || '-'} />
            <InfoField
              label="비용합계"
              value={formatAmount(item.total_cost)}
              valueClassName="text-red-600"
            />
          </div>
        }
        actions={
          isSelected ? (
            <div className="flex gap-2 flex-wrap">
              <Button
                variant="outline"
                size="default"
                className="flex-1 min-w-[100px] h-11"
                onClick={(e) => { e.stopPropagation(); handleView(item); }}
              >
                <Eye className="h-4 w-4 mr-2" />
                상세
              </Button>
              <Button
                variant="default"
                size="default"
                className="flex-1 min-w-[100px] h-11"
                onClick={(e) => { e.stopPropagation(); handleEdit(item); }}
              >
                <Edit className="h-4 w-4 mr-2" />
                수정
              </Button>
              {item.status !== 'CLOSED' && (
                <Button
                  variant="outline"
                  size="default"
                  className="flex-1 min-w-[100px] h-11 border-red-200 text-red-600 hover:border-red-300"
                  onClick={(e) => { e.stopPropagation(); handleDelete(String(item.id)); }}
                >
                  <Trash2 className="h-4 w-4 mr-2" />
                  삭제
                </Button>
              )}
            </div>
          ) : undefined
        }
      />
    );
  };

  // Config
  const config: UniversalListConfig<NonconformingListItem> = {
    title: '부적합관리',
    description: '부적합 보고서 등록 및 관리',
    icon: AlertTriangle,
    basePath: BASE_PATH,
    idField: 'id',

    actions: {
      getList: async () => ({
        success: true,
        data,
        totalCount,
      }),
      deleteItem: async (id) => {
        const result = await deleteNonconformingReport(id);
        if (result.success) loadData();
        return result;
      },
    },

    columns: tableColumns,

    computeStats: () => stats,

    searchPlaceholder: '부적합번호, 현장명, 품목명 검색...',

    dateRangeSelector: {
      enabled: true,
      showPresets: true,
      presetsPosition: 'inline',
      startDate,
      endDate,
      onStartDateChange: (d: string) => { setStartDate(d); setCurrentPage(1); },
      onEndDateChange: (d: string) => { setEndDate(d); setCurrentPage(1); },
      dateField: 'occurred_at',
    },

    itemsPerPage,

    clientSideFiltering: false,

    filterConfig,
    initialFilters: filterValues,
    filterTitle: '부적합 필터',

    headerActions: () => (
      <Button onClick={() => router.push(`${BASE_PATH}?mode=new`)}>
        <Plus className="w-4 h-4 mr-2" />
        부적합 등록
      </Button>
    ),

    renderTableRow,
    renderMobileCard,

    renderDialogs: () => (
      <DeleteConfirmDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
        onConfirm={handleConfirmDelete}
        title="삭제 확인"
        description={
          <>
            선택한 부적합 보고서를 삭제하시겠습니까?
            <br />
            <span className="text-muted-foreground text-sm">
              삭제된 보고서는 복구할 수 없습니다.
            </span>
          </>
        }
        loading={isDeleting}
      />
    ),
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
          <p className="text-muted-foreground">부적합 목록을 불러오는 중...</p>
        </div>
      </div>
    );
  }

  return (
    <UniversalListPage<NonconformingListItem>
      config={config}
      initialData={data}
      initialTotalCount={totalCount}
      externalSelection={{
        selectedItems,
        onToggleSelection: toggleSelection,
        onToggleSelectAll: toggleSelectAll,
        setSelectedItems,
        getItemId: (item) => String(item.id),
      }}
      externalPagination={{
        currentPage,
        totalPages: Math.ceil(totalCount / itemsPerPage),
        totalItems: totalCount,
        itemsPerPage,
        onPageChange: (page: number) => setCurrentPage(page),
      }}
      onFilterChange={(newFilters) => {
        setFilterValues(newFilters);
        setCurrentPage(1);
      }}
      onSearchChange={(q: string) => {
        setSearchTerm(q);
        setCurrentPage(1);
      }}
    />
  );
}
