'use client';

/**
 * 이슈관리 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 클라이언트 사이드 필터링 (검색, 필터, 정렬)
 * - Stats 카드 클릭 필터링 (activeStatTab)
 * - DateRangeSelector + 등록 버튼 (dateRangeSelector + createButton)
 * - filterConfig (multi: 거래처, 현장명, 구분, 보고자, 담당자 / single: 중요도, 상태, 정렬)
 * - 철회 기능 (tableHeaderActions로 구현)
 */

import { useState, useMemo, useCallback, useEffect } from 'react';
import { AlertTriangle, Pencil, Inbox, Clock, CheckCircle, XCircle, Undo2 } from 'lucide-react';
import { useListHandlers } from '@/hooks/useListHandlers';
import { Button } from '@/components/ui/button';
import { TableCell, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import { MobileCard } from '@/components/organisms/MobileCard';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { toast } from 'sonner';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type StatCard,
} from '@/components/templates/UniversalListPage';
import type { Issue, IssueStats } from './types';
import {
  ISSUE_STATUS_OPTIONS,
  ISSUE_PRIORITY_OPTIONS,
  ISSUE_CATEGORY_OPTIONS,
  ISSUE_SORT_OPTIONS,
  ISSUE_STATUS_STYLES,
  ISSUE_STATUS_LABELS,
  ISSUE_PRIORITY_STYLES,
  ISSUE_PRIORITY_LABELS,
  ISSUE_CATEGORY_LABELS,
  MOCK_ISSUE_PARTNERS,
  MOCK_ISSUE_SITES,
  MOCK_ISSUE_REPORTERS,
  MOCK_ISSUE_ASSIGNEES,
} from './types';
import {
  getIssueList,
  getIssueStats,
  withdrawIssues,
} from './actions';
import { formatDate } from '@/lib/utils/date';
import { useDateRange } from '@/hooks';

// 테이블 컬럼 정의
const tableColumns = [
  { key: 'no', label: '번호', className: 'w-[50px] text-center' },
  { key: 'issueNumber', label: '이슈번호', className: 'w-[120px]', copyable: true },
  { key: 'constructionNumber', label: '시공번호', className: 'w-[100px]', copyable: true },
  { key: 'partnerName', label: '거래처', className: 'w-[100px]', copyable: true },
  { key: 'siteName', label: '현장', className: 'min-w-[120px]', copyable: true },
  { key: 'category', label: '구분', className: 'w-[80px] text-center', copyable: true },
  { key: 'title', label: '제목', className: 'min-w-[150px]', copyable: true },
  { key: 'reporter', label: '보고자', className: 'w-[80px]', copyable: true },
  { key: 'reportDate', label: '이슈보고일', className: 'w-[100px]', copyable: true },
  { key: 'resolvedDate', label: '이슈해결일', className: 'w-[100px]', copyable: true },
  { key: 'assignee', label: '담당자', className: 'w-[80px]', copyable: true },
  { key: 'priority', label: '중요도', className: 'w-[80px] text-center' },
  { key: 'status', label: '상태', className: 'w-[80px] text-center' },
  { key: 'actions', label: '작업', className: 'w-[80px] text-center' },
];

interface IssueManagementListClientProps {
  initialData?: Issue[];
  initialStats?: IssueStats;
}

export default function IssueManagementListClient({
  initialData = [],
  initialStats,
}: IssueManagementListClientProps) {
  // ===== 공통 핸들러 Hook =====
  const { handleRowClick, handleEdit, router } = useListHandlers<Issue>(
    'construction/project/issue-management'
  );

  // ===== 외부 상태 (UniversalListPage 외부에서 관리) =====
  const [activeStatTab, setActiveStatTab] = useState<'all' | 'received' | 'in_progress' | 'resolved' | 'unresolved'>('all');
  const { startDate, endDate, setStartDate, setEndDate } = useDateRange('today');
  const [stats, setStats] = useState<IssueStats | null>(initialStats || null);
  const [searchQuery, setSearchQuery] = useState('');
  const [withdrawDialogOpen, setWithdrawDialogOpen] = useState(false);
  const [itemsToWithdraw, setItemsToWithdraw] = useState<Set<string>>(new Set());
  const [clearSelectionFn, setClearSelectionFn] = useState<(() => void) | null>(null);

  // Stats 로드
  useEffect(() => {
    if (!initialStats) {
      getIssueStats().then((result) => {
        if (result.success && result.data) {
          setStats(result.data);
        }
      });
    }
  }, [initialStats]);

  // ===== 추가 핸들러 =====
  const handleCreate = useCallback(() => {
    router.push('/ko/construction/project/issue-management?mode=new');
  }, [router]);

  // 철회 다이얼로그 열기
  const handleWithdrawClick = useCallback((selectedItems: Set<string>, onClearSelection: () => void) => {
    if (selectedItems.size === 0) {
      toast.error('철회할 이슈를 선택해주세요.');
      return;
    }
    setItemsToWithdraw(new Set(selectedItems));
    setClearSelectionFn(() => onClearSelection);
    setWithdrawDialogOpen(true);
  }, []);

  // 철회 실행
  const handleWithdraw = useCallback(async () => {
    try {
      const ids = Array.from(itemsToWithdraw);
      const result = await withdrawIssues(ids);
      if (result.success) {
        toast.success(`${ids.length}건의 이슈가 철회되었습니다.`);
        clearSelectionFn?.();
      } else {
        toast.error(result.error || '이슈 철회에 실패했습니다.');
      }
    } catch {
      toast.error('이슈 철회에 실패했습니다.');
    } finally {
      setWithdrawDialogOpen(false);
      setItemsToWithdraw(new Set());
    }
  }, [itemsToWithdraw, clearSelectionFn]);

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<Issue> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '이슈관리',
      description: '이슈 목록을 관리합니다',
      icon: AlertTriangle,
      basePath: '/construction/project/issue-management',

      // ID 추출
      idField: 'id',

      // API 액션
      actions: {
        getList: async () => {
          const result = await getIssueList({
            size: 1000,
            startDate: startDate || undefined,
            endDate: endDate || undefined,
          });
          if (result.success && result.data) {
            return {
              success: true,
              data: result.data.items,
              totalCount: result.data.total,
            };
          }
          return { success: false, error: result.error };
        },
      },

      // 테이블 컬럼
      columns: tableColumns,

      // 클라이언트 사이드 필터링
      clientSideFiltering: true,
      itemsPerPage: 20,

      // 검색 필터
      searchPlaceholder: '이슈번호, 시공번호, 거래처, 현장, 제목, 보고자, 담당자 검색',
      searchFilter: (item, searchValue) => {
        const search = searchValue.toLowerCase();
        return (
          item.issueNumber.toLowerCase().includes(search) ||
          item.constructionNumber.toLowerCase().includes(search) ||
          item.partnerName.toLowerCase().includes(search) ||
          item.siteName.toLowerCase().includes(search) ||
          item.title.toLowerCase().includes(search) ||
          item.reporter.toLowerCase().includes(search) ||
          item.assignee.toLowerCase().includes(search)
        );
      },

      // 필터 설정
      filterConfig: [
        {
          key: 'partner',
          label: '거래처',
          type: 'multi',
          options: MOCK_ISSUE_PARTNERS,
        },
        {
          key: 'site',
          label: '현장명',
          type: 'multi',
          options: MOCK_ISSUE_SITES,
        },
        {
          key: 'category',
          label: '구분',
          type: 'multi',
          options: ISSUE_CATEGORY_OPTIONS.filter((c) => c.value !== 'all'),
        },
        {
          key: 'reporter',
          label: '보고자',
          type: 'multi',
          options: MOCK_ISSUE_REPORTERS,
        },
        {
          key: 'assignee',
          label: '담당자',
          type: 'multi',
          options: MOCK_ISSUE_ASSIGNEES,
        },
        {
          key: 'priority',
          label: '중요도',
          type: 'single',
          options: ISSUE_PRIORITY_OPTIONS.filter((o) => o.value !== 'all'),
        },
        {
          key: 'status',
          label: '상태',
          type: 'single',
          options: ISSUE_STATUS_OPTIONS.filter((o) => o.value !== 'all'),
        },
        {
          key: 'sortBy',
          label: '정렬',
          type: 'single',
          options: ISSUE_SORT_OPTIONS,
        },
      ],
      initialFilters: {
        partner: [],
        site: [],
        category: [],
        reporter: [],
        assignee: [],
        priority: 'all',
        status: 'all',
        sortBy: 'latest',
      },
      filterTitle: '이슈 필터',

      // 커스텀 필터 함수
      customFilterFn: (items, filterValues) => {
        if (!items || items.length === 0) return items;
        return items.filter((item) => {
          // Stats 탭 필터
          if (activeStatTab !== 'all' && item.status !== activeStatTab) return false;

          // 거래처 필터 (다중선택)
          const partnerFilters = filterValues.partner as string[];
          if (partnerFilters?.length > 0) {
            const matchingPartner = MOCK_ISSUE_PARTNERS.find((p) => p.label === item.partnerName);
            if (!matchingPartner || !partnerFilters.includes(matchingPartner.value)) return false;
          }

          // 현장 필터 (다중선택)
          const siteFilters = filterValues.site as string[];
          if (siteFilters?.length > 0) {
            const matchingSite = MOCK_ISSUE_SITES.find((s) => s.label === item.siteName);
            if (!matchingSite || !siteFilters.includes(matchingSite.value)) return false;
          }

          // 구분 필터 (다중선택)
          const categoryFilters = filterValues.category as string[];
          if (categoryFilters?.length > 0 && !categoryFilters.includes(item.category)) return false;

          // 보고자 필터 (다중선택)
          const reporterFilters = filterValues.reporter as string[];
          if (reporterFilters?.length > 0) {
            const matchingReporter = MOCK_ISSUE_REPORTERS.find((r) => r.label === item.reporter);
            if (!matchingReporter || !reporterFilters.includes(matchingReporter.value)) return false;
          }

          // 담당자 필터 (다중선택)
          const assigneeFilters = filterValues.assignee as string[];
          if (assigneeFilters?.length > 0) {
            const matchingAssignee = MOCK_ISSUE_ASSIGNEES.find((a) => a.label === item.assignee);
            if (!matchingAssignee || !assigneeFilters.includes(matchingAssignee.value)) return false;
          }

          // 중요도 필터 (단일선택)
          const priorityFilter = filterValues.priority as string;
          if (priorityFilter && priorityFilter !== 'all' && item.priority !== priorityFilter) return false;

          // 상태 필터 (단일선택)
          const statusFilter = filterValues.status as string;
          if (statusFilter && statusFilter !== 'all' && item.status !== statusFilter) return false;

          return true;
        });
      },

      // 커스텀 정렬 함수
      customSortFn: (items, filterValues) => {
        const sorted = [...items];
        const sortBy = (filterValues.sortBy as string) || 'latest';

        switch (sortBy) {
          case 'oldest':
            sorted.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
            break;
          case 'reportDate':
            sorted.sort((a, b) => new Date(b.reportDate).getTime() - new Date(a.reportDate).getTime());
            break;
          case 'priorityHigh': {
            const priorityOrderHigh: Record<string, number> = { urgent: 0, normal: 1 };
            sorted.sort((a, b) => (priorityOrderHigh[a.priority] ?? 2) - (priorityOrderHigh[b.priority] ?? 2));
            break;
          }
          case 'priorityLow': {
            const priorityOrderLow: Record<string, number> = { urgent: 1, normal: 0 };
            sorted.sort((a, b) => (priorityOrderLow[a.priority] ?? 2) - (priorityOrderLow[b.priority] ?? 2));
            break;
          }
          default: // latest
            sorted.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
            break;
        }
        return sorted;
      },

      // 검색창 (공통 컴포넌트에서 자동 생성)
      hideSearch: true,
      searchValue: searchQuery,
      onSearchChange: setSearchQuery,

      // 공통 헤더 옵션
      dateRangeSelector: {
        enabled: true,
        startDate,
        endDate,
        onStartDateChange: setStartDate,
        onEndDateChange: setEndDate,
      },
      createButton: {
        label: '이슈 등록',
        onClick: handleCreate,
      },

      // Stats 카드
      computeStats: (): StatCard[] => [
        {
          label: '접수',
          value: stats?.received ?? 0,
          icon: Inbox,
          iconColor: 'text-blue-600',
          onClick: () => setActiveStatTab('received'),
          isActive: activeStatTab === 'received',
        },
        {
          label: '처리중',
          value: stats?.inProgress ?? 0,
          icon: Clock,
          iconColor: 'text-yellow-600',
          onClick: () => setActiveStatTab('in_progress'),
          isActive: activeStatTab === 'in_progress',
        },
        {
          label: '해결완료',
          value: stats?.resolved ?? 0,
          icon: CheckCircle,
          iconColor: 'text-green-600',
          onClick: () => setActiveStatTab('resolved'),
          isActive: activeStatTab === 'resolved',
        },
        {
          label: '미해결',
          value: stats?.unresolved ?? 0,
          icon: XCircle,
          iconColor: 'text-red-600',
          onClick: () => setActiveStatTab('unresolved'),
          isActive: activeStatTab === 'unresolved',
        },
      ],

      // 테이블 헤더 액션 (철회 버튼)
      tableHeaderActions: ({ selectedItems, onClearSelection }) =>
        selectedItems.size > 0 ? (
          <Button
            variant="outline"
            size="sm"
            onClick={() => handleWithdrawClick(selectedItems, onClearSelection)}
            className="text-orange-600 border-orange-300 hover:bg-orange-50"
          >
            <Undo2 className="mr-2 h-4 w-4" />
            철회 ({selectedItems.size})
          </Button>
        ) : null,

      // 테이블 행 렌더링
      renderTableRow: (
        item: Issue,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Issue>
      ) => (
        <TableRow
          key={item.id}
          className="cursor-pointer hover:bg-muted/50"
          onClick={() => handleRowClick(item)}
        >
          <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
            <Checkbox checked={handlers.isSelected} onCheckedChange={handlers.onToggle} />
          </TableCell>
          <TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
          <TableCell>{item.issueNumber}</TableCell>
          <TableCell>{item.constructionNumber}</TableCell>
          <TableCell>{item.partnerName}</TableCell>
          <TableCell>{item.siteName}</TableCell>
          <TableCell className="text-center">
            <span className="px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-700">
              {ISSUE_CATEGORY_LABELS[item.category]}
            </span>
          </TableCell>
          <TableCell className="max-w-[200px] truncate" title={item.title}>{item.title}</TableCell>
          <TableCell>{item.reporter}</TableCell>
          <TableCell>{formatDate(item.reportDate)}</TableCell>
          <TableCell>{formatDate(item.resolvedDate)}</TableCell>
          <TableCell>{item.assignee}</TableCell>
          <TableCell className="text-center">
            <span className={`px-2 py-1 rounded-full text-xs font-medium ${ISSUE_PRIORITY_STYLES[item.priority]}`}>
              {ISSUE_PRIORITY_LABELS[item.priority]}
            </span>
          </TableCell>
          <TableCell className="text-center">
            <span className={`px-2 py-1 rounded-full text-xs font-medium ${ISSUE_STATUS_STYLES[item.status]}`}>
              {ISSUE_STATUS_LABELS[item.status]}
            </span>
          </TableCell>
          <TableCell className="text-center">
            {handlers.isSelected && (
              <div className="flex items-center justify-center gap-1">
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-8 w-8"
                  onClick={(e) => {
                    e.stopPropagation();
                    handleEdit(item);
                  }}
                >
                  <Pencil className="h-4 w-4" />
                </Button>
              </div>
            )}
          </TableCell>
        </TableRow>
      ),

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: Issue,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Issue>
      ) => (
        <MobileCard
          key={item.id}
          title={item.title}
          subtitle={item.issueNumber}
          badge={ISSUE_STATUS_LABELS[item.status]}
          badgeVariant="secondary"
          isSelected={handlers.isSelected}
          onToggle={handlers.onToggle}
          onClick={() => handleRowClick(item)}
          details={[
            { label: '거래처', value: item.partnerName },
            { label: '현장', value: item.siteName },
            { label: '보고일', value: formatDate(item.reportDate) },
            { label: '중요도', value: ISSUE_PRIORITY_LABELS[item.priority] },
          ]}
        />
      ),
    }),
    [startDate, endDate, searchQuery, activeStatTab, stats, handleRowClick, handleEdit, handleCreate, handleWithdrawClick]
  );

  return (
    <>
      <UniversalListPage config={config} initialData={initialData} onSearchChange={setSearchQuery} />

      {/* 철회 확인 다이얼로그 */}
      <ConfirmDialog
        open={withdrawDialogOpen}
        onOpenChange={setWithdrawDialogOpen}
        onConfirm={handleWithdraw}
        variant="warning"
        title="이슈 철회"
        description={
          <>
            선택한 <strong>{itemsToWithdraw.size}건</strong>의 이슈를 철회하시겠습니까?
            <br />
            철회된 이슈는 복구할 수 없습니다.
          </>
        }
        confirmText="철회"
      />
    </>
  );
}
