'use client';

/**
 * 실적신고 목록 페이지
 *
 * 탭 2개 (above-stats 위치):
 * - 분기별 실적신고: 연도+분기 버튼 필터, 검색, 통계 카드 4개, 액션 버튼, 테이블
 * - 누락체크: 설명 박스 + 누락 목록 테이블
 *
 * UniversalListPage 공통 템플릿 사용
 */

import { useState, useEffect, useMemo, useCallback } from 'react';
import {
  FileText,
  ClipboardList,
  CheckCircle2,
  XCircle,
  MapPin,
  Check,
  Undo2,
  Send,
  Pencil,
  Download,
  AlertTriangle,
} from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { TableCell, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import { YearQuarterFilter } from '@/components/molecules/YearQuarterFilter';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type StatCard,
  type ListParams,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { MemoModal } from './MemoModal';
import {
  getPerformanceReports,
  getPerformanceReportStats,
  getMissedReports,
  confirmReports,
  unconfirmReports,
  distributeReports,
  updateMemo,
  exportConfirmedExcel,
} from './actions';
import { confirmStatusColorMap } from './mockData';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import type {
  PerformanceReportStats,
  ReportListItem,
  Quarter,
} from './types';

const ITEMS_PER_PAGE = 20;

export function PerformanceReportList() {
  // ===== 통계 =====
  const [statsData, setStatsData] = useState<PerformanceReportStats>({
    totalCount: 0,
    confirmedCount: 0,
    unconfirmedCount: 0,
    totalLocations: 0,
  });

  // ===== 연도/분기 필터 =====
  const currentYear = new Date().getFullYear();
  const [year, setYear] = useState(currentYear);
  const [quarter, setQuarter] = useState<Quarter | '전체'>('전체');

  // ===== 메모 모달 =====
  const [isMemoModalOpen, setIsMemoModalOpen] = useState(false);
  const [memoSelectedIds, setMemoSelectedIds] = useState<string[]>([]);
  const [memoTotalLocations, setMemoTotalLocations] = useState(0);

  // ===== 리프레시 트리거 =====
  const [refreshKey, setRefreshKey] = useState(0);

  // ===== 현재 탭 추적 (headerActions에서 사용) =====
  const [currentTab, setCurrentTab] = useState('quarterly');

  // ===== 현재 데이터 추적 (메모 모달 개소 계산용) =====
  const [currentData, setCurrentData] = useState<ReportListItem[]>([]);

  // ===== 통계 로드 =====
  useEffect(() => {
    const loadStats = async () => {
      try {
        const result = await getPerformanceReportStats({ year, quarter });
        if (result.success && result.data) {
          setStatsData(result.data);
        }
      } catch (error) {
        if (isNextRedirectError(error)) throw error;
        console.error('[PerformanceReportList] loadStats error:', error);
      }
    };
    loadStats();
  }, [year, quarter, refreshKey]);

  // ===== 액션 핸들러 =====
  const handleConfirm = useCallback(async (
    selectedItems: Set<string>,
    onClearSelection: () => void,
    onRefresh: () => void
  ) => {
    if (selectedItems.size === 0) {
      toast.error('확정할 항목을 선택해주세요.');
      return;
    }
    try {
      const result = await confirmReports(Array.from(selectedItems));
      if (result.success) {
        toast.success(`${selectedItems.size}건이 확정되었습니다.`);
        onClearSelection();
        onRefresh();
        setRefreshKey((k) => k + 1);
      } else {
        toast.error(result.error || '확정 처리에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('서버 오류가 발생했습니다.');
    }
  }, []);

  const handleUnconfirm = useCallback(async (
    selectedItems: Set<string>,
    onClearSelection: () => void,
    onRefresh: () => void
  ) => {
    if (selectedItems.size === 0) {
      toast.error('확정 해제할 항목을 선택해주세요.');
      return;
    }
    try {
      const result = await unconfirmReports(Array.from(selectedItems));
      if (result.success) {
        toast.success(`${selectedItems.size}건의 확정이 해제되었습니다.`);
        onClearSelection();
        onRefresh();
        setRefreshKey((k) => k + 1);
      } else {
        toast.error(result.error || '확정 해제에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('서버 오류가 발생했습니다.');
    }
  }, []);

  const handleDistribute = useCallback(async (
    selectedItems: Set<string>,
    onClearSelection: () => void,
    onRefresh: () => void
  ) => {
    if (selectedItems.size === 0) {
      toast.error('배포할 항목을 선택해주세요.');
      return;
    }
    try {
      const result = await distributeReports(Array.from(selectedItems));
      if (result.success) {
        toast.success(`${selectedItems.size}건이 배포되었습니다.`);
        onClearSelection();
        onRefresh();
        setRefreshKey((k) => k + 1);
      } else {
        toast.error(result.error || '배포에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('서버 오류가 발생했습니다.');
    }
  }, []);

  const handleOpenMemoModal = useCallback((selectedItems: Set<string>) => {
    const ids = Array.from(selectedItems);
    if (ids.length === 0) {
      toast.error('메모를 작성할 항목을 선택해주세요.');
      return;
    }
    setMemoSelectedIds(ids);
    const totalLoc = currentData
      .filter((r) => selectedItems.has(r.id))
      .reduce((sum, r) => sum + r.locationCount, 0);
    setMemoTotalLocations(totalLoc);
    setIsMemoModalOpen(true);
  }, [currentData]);

  const handleMemoSubmit = useCallback(async (memo: string) => {
    if (memoSelectedIds.length === 0) return;
    try {
      const result = await updateMemo(memoSelectedIds, memo);
      if (result.success) {
        toast.success(`${memoSelectedIds.length}건에 메모가 적용되었습니다.`);
        setRefreshKey((k) => k + 1);
      } else {
        toast.error(result.error || '메모 저장에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('서버 오류가 발생했습니다.');
    }
  }, [memoSelectedIds]);

  const handleExcelDownload = useCallback(async () => {
    const quarterNum = quarter === '전체' ? Math.ceil(new Date().getMonth() / 3) || 1 : Number(quarter);
    try {
      const result = await exportConfirmedExcel({ year, quarter: quarterNum });
      if (result.success && result.data) {
        const url = URL.createObjectURL(result.data);
        const a = document.createElement('a');
        a.href = url;
        a.download = result.filename || `판매실적대장_${year}년_${quarterNum}분기.xlsx`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        toast.success('엑셀 다운로드 완료');
      } else {
        toast.error(result.error || '엑셀 다운로드에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('엑셀 다운로드에 실패했습니다.');
    }
  }, [year, quarter]);

  // ===== 통계 카드 =====
  const stats: StatCard[] = useMemo(
    () => [
      {
        label: '전체',
        value: statsData.totalCount,
        icon: ClipboardList,
        iconColor: 'text-gray-600',
      },
      {
        label: '확정',
        value: statsData.confirmedCount,
        icon: CheckCircle2,
        iconColor: 'text-green-600',
      },
      {
        label: '미확정',
        value: statsData.unconfirmedCount,
        icon: XCircle,
        iconColor: 'text-orange-600',
      },
      {
        label: '총 개소',
        value: statsData.totalLocations,
        icon: MapPin,
        iconColor: 'text-blue-600',
      },
    ],
    [statsData]
  );

  // ===== 연도/분기 필터 슬롯 (dateRangeSelector.extraActions) =====
  const quarterFilterSlot = useMemo(
    () => (
      <YearQuarterFilter
        year={year}
        quarter={quarter}
        onYearChange={setYear}
        onQuarterChange={setQuarter}
        className="order-first"
      />
    ),
    [year, quarter]
  );

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<ReportListItem> = useMemo(
    () => ({
      title: '실적신고 목록',
      description: '분기별 실적신고 및 누락체크를 관리합니다',
      icon: FileText,
      basePath: '/quality/performance-reports',
      idField: 'id',
      detailMode: 'none' as const,

      // API 액션
      actions: {
        getList: async (params?: ListParams) => {
          try {
            const tab = params?.tab || 'quarterly';

            if (tab === 'missed') {
              const result = await getMissedReports({
                page: params?.page || 1,
                size: params?.pageSize || ITEMS_PER_PAGE,
                q: params?.search || undefined,
              });
              if (result.success) {
                const mapped: ReportListItem[] = result.data.map((r) => ({
                  id: r.id,
                  qualityDocNumber: r.qualityDocNumber,
                  siteName: r.siteName,
                  client: r.client,
                  locationCount: r.locationCount,
                  memo: r.memo,
                  inspectionCompleteDate: r.inspectionCompleteDate,
                }));
                return {
                  success: true,
                  data: mapped,
                  totalCount: result.pagination.total,
                  totalPages: result.pagination.lastPage,
                };
              }
              return { success: false, error: result.error };
            }

            // quarterly tab
            const result = await getPerformanceReports({
              page: params?.page || 1,
              size: params?.pageSize || ITEMS_PER_PAGE,
              q: params?.search || undefined,
              year,
              quarter,
            });

            if (result.success) {
              // 통계 갱신
              const statsResult = await getPerformanceReportStats({ year, quarter });
              if (statsResult.success && statsResult.data) {
                setStatsData(statsResult.data);
              }

              const mapped: ReportListItem[] = result.data.map((r) => ({
                id: r.id,
                qualityDocNumber: r.qualityDocNumber,
                siteName: r.siteName,
                client: r.client,
                locationCount: r.locationCount,
                memo: r.memo,
                createdDate: r.createdDate,
                requiredInfo: r.requiredInfo,
                confirmStatus: r.confirmStatus,
                confirmDate: r.confirmDate,
                year: r.year,
                quarter: r.quarter,
              }));
              return {
                success: true,
                data: mapped,
                totalCount: result.pagination.total,
                totalPages: result.pagination.lastPage,
              };
            }
            return { success: false, error: result.error };
          } catch (error) {
            if (isNextRedirectError(error)) throw error;
            return { success: false, error: '데이터 로드 중 오류가 발생했습니다.' };
          }
        },
      },

      // 탭
      tabs: [
        { value: 'quarterly', label: '분기별 실적신고', count: 0 },
        { value: 'missed', label: '누락체크', count: 0 },
      ],
      defaultTab: 'quarterly',
      tabsPosition: 'above-stats',

      // 탭별 컬럼
      columnsPerTab: {
        quarterly: [
          { key: 'no', label: '번호', className: 'w-[60px] text-center' },
          { key: 'qualityDocNumber', label: '품질관리서 번호', className: 'min-w-[130px]', copyable: true },
          { key: 'createdDate', label: '작성일', className: 'w-[100px]', copyable: true },
          { key: 'siteName', label: '현장명', className: 'min-w-[120px]', copyable: true },
          { key: 'client', label: '수주처', className: 'min-w-[80px]', copyable: true },
          { key: 'locationCount', label: '개소', className: 'w-[60px] text-center', copyable: true },
          { key: 'requiredInfo', label: '필수정보', className: 'w-[90px] text-center', copyable: true },
          { key: 'confirmStatus', label: '확정상태', className: 'w-[80px] text-center' },
          { key: 'confirmDate', label: '확정일', className: 'w-[100px]', copyable: true },
          { key: 'memo', label: '메모', className: 'min-w-[120px]', copyable: true },
        ],
        missed: [
          { key: 'no', label: '번호', className: 'w-[60px] text-center' },
          { key: 'qualityDocNumber', label: '품질관리서 번호', className: 'min-w-[130px]', copyable: true },
          { key: 'siteName', label: '현장명', className: 'min-w-[120px]', copyable: true },
          { key: 'client', label: '수주처', className: 'min-w-[80px]', copyable: true },
          { key: 'locationCount', label: '개소', className: 'w-[60px] text-center', copyable: true },
          { key: 'inspectionCompleteDate', label: '제품검사완료일', className: 'w-[120px]', copyable: true },
          { key: 'memo', label: '메모', className: 'min-w-[120px]', copyable: true },
        ],
      },
      columns: [], // columnsPerTab 사용

      // 날짜 범위 선택기 → 연도/분기 필터
      dateRangeSelector: {
        enabled: true,
        hideDateInputs: true,
        showPresets: false,
        extraActions: quarterFilterSlot,
      },

      // 통계 (quarterly 탭만)
      stats: currentTab === 'quarterly' ? stats : undefined,

      // 검색
      searchPlaceholder: '품질관리서 번호, 현장명, 수주처 검색...',
      clientSideFiltering: false,
      itemsPerPage: ITEMS_PER_PAGE,

      // 체크박스 항상 표시
      showCheckbox: true,

      // 누락체크 탭: 경고 배너
      beforeTableContent: currentTab === 'missed' ? (
        <div className="flex items-start gap-3 p-4 rounded-lg border border-amber-200 bg-amber-50">
          <AlertTriangle className="h-5 w-5 text-amber-600 mt-0.5 shrink-0" />
          <div className="text-sm text-amber-800 space-y-1">
            <p className="font-medium">누락체크 안내</p>
            <p>
              제품검사가 완료되었으나 실적신고에 포함되지 않은 건을 표시합니다.
              해당 건들을 확인하여 실적신고에 반영해주세요.
            </p>
          </div>
        </div>
      ) : undefined,

      // 선택 액션 (체크박스 선택 시 테이블 좌측에 표시)
      selectionActions: ({ selectedItems, onClearSelection, onRefresh }) => {
        if (currentTab !== 'quarterly') return null;
        return (
          <>
            <Button size="sm" onClick={() => handleConfirm(selectedItems, onClearSelection, onRefresh)}>
              <Check className="h-4 w-4 mr-1" />
              선택 확정
            </Button>
            <Button size="sm" variant="outline" onClick={() => handleUnconfirm(selectedItems, onClearSelection, onRefresh)}>
              <Undo2 className="h-4 w-4 mr-1" />
              확정 해제
            </Button>
            <Button size="sm" variant="outline" onClick={() => handleDistribute(selectedItems, onClearSelection, onRefresh)}>
              <Send className="h-4 w-4 mr-1" />
              배포
            </Button>
            <Button size="sm" variant="outline" onClick={() => handleOpenMemoModal(selectedItems)}>
              <Pencil className="h-4 w-4 mr-1" />
              메모
            </Button>
          </>
        );
      },

      // 헤더 액션 (항상 표시)
      headerActions: () => {
        if (currentTab !== 'quarterly') return null;
        return (
          <div className="flex items-center gap-2 flex-wrap">
            <Button size="sm" variant="outline" onClick={handleExcelDownload}>
              <Download className="h-4 w-4 mr-1" />
              확정건 엑셀다운로드
            </Button>
          </div>
        );
      },

      // 데이터 변경 콜백 (메모 모달용)
      onDataChange: (data) => {
        setCurrentData(data);
      },

      // 테이블 행 렌더링
      renderTableRow: (
        item: ReportListItem,
        _index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<ReportListItem>
      ) => {
        // quarterly 탭 렌더링
        if (item.createdDate !== undefined) {
          const isRequiredMissing = item.requiredInfo && item.requiredInfo !== '입력완료';

          return (
            <TableRow
              key={item.id}
              className={handlers.isSelected ? 'bg-blue-50' : ''}
            >
              <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 className="font-medium">{item.qualityDocNumber}</TableCell>
              <TableCell>{item.createdDate}</TableCell>
              <TableCell>{item.siteName}</TableCell>
              <TableCell>{item.client}</TableCell>
              <TableCell className="text-center">{item.locationCount}</TableCell>
              <TableCell className="text-center">
                {item.requiredInfo && (
                  <span className={isRequiredMissing ? 'text-red-600 font-medium' : 'text-green-600'}>
                    {item.requiredInfo}
                  </span>
                )}
              </TableCell>
              <TableCell className="text-center">
                {item.confirmStatus && (
                  <Badge className={`text-xs ${confirmStatusColorMap[item.confirmStatus]} border-0`}>
                    {item.confirmStatus}
                  </Badge>
                )}
              </TableCell>
              <TableCell>{item.confirmDate || '-'}</TableCell>
              <TableCell className="text-muted-foreground text-sm truncate max-w-[200px]">
                {item.memo || '-'}
              </TableCell>
            </TableRow>
          );
        }

        // missed 탭 렌더링
        return (
          <TableRow
            key={item.id}
            className={handlers.isSelected ? 'bg-blue-50' : ''}
          >
            <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 className="font-medium">{item.qualityDocNumber}</TableCell>
            <TableCell>{item.siteName}</TableCell>
            <TableCell>{item.client}</TableCell>
            <TableCell className="text-center">{item.locationCount}</TableCell>
            <TableCell>{item.inspectionCompleteDate}</TableCell>
            <TableCell className="text-muted-foreground text-sm truncate max-w-[200px]">
              {item.memo || '-'}
            </TableCell>
          </TableRow>
        );
      },

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: ReportListItem,
        _index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<ReportListItem>
      ) => {
        const isQuarterly = item.createdDate !== undefined;

        return (
          <ListMobileCard
            key={item.id}
            id={item.id}
            isSelected={handlers.isSelected}
            onToggleSelection={handlers.onToggle}
            headerBadges={
              <>
                <Badge variant="outline" className="text-xs">{globalIndex}</Badge>
                <Badge variant="outline" className="text-xs">{item.qualityDocNumber}</Badge>
              </>
            }
            title={item.siteName}
            statusBadge={
              isQuarterly && item.confirmStatus ? (
                <Badge className={`text-xs ${confirmStatusColorMap[item.confirmStatus]} border-0`}>
                  {item.confirmStatus}
                </Badge>
              ) : undefined
            }
            infoGrid={
              <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                <InfoField label="수주처" value={item.client} />
                <InfoField label="개소" value={String(item.locationCount)} />
                {isQuarterly ? (
                  <>
                    <InfoField label="작성일" value={item.createdDate || '-'} />
                    <InfoField label="필수정보" value={item.requiredInfo || '-'} />
                    <InfoField label="확정상태" value={item.confirmStatus || '-'} />
                    <InfoField label="확정일" value={item.confirmDate || '-'} />
                  </>
                ) : (
                  <InfoField label="제품검사완료일" value={item.inspectionCompleteDate || '-'} />
                )}
                <InfoField label="메모" value={item.memo || '-'} />
              </div>
            }
          />
        );
      },
    }),
    [stats, quarterFilterSlot, currentTab, year, quarter, refreshKey, handleConfirm, handleUnconfirm, handleDistribute, handleOpenMemoModal, handleExcelDownload]
  );

  return (
    <>
      <UniversalListPage
        config={config}
        onTabChange={(tab) => setCurrentTab(tab)}
      />

      {/* 메모 모달 */}
      <MemoModal
        isOpen={isMemoModalOpen}
        onClose={() => setIsMemoModalOpen(false)}
        selectedCount={memoSelectedIds.length}
        totalLocations={memoTotalLocations}
        onSubmit={handleMemoSubmit}
      />
    </>
  );
}
