'use client';

/**
 * 결제내역 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 서버 사이드 페이지네이션 (getPayments API)
 * - 검색 숨김, 체크박스 숨김
 */

import { useState, useMemo, useCallback } from 'react';
import { Receipt, FileText } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { TableRow, TableCell } from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type ListParams,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard } from '@/components/organisms/MobileCard';
import { getPayments } from './actions';
import { formatNumber } from '@/lib/utils/amount';
import type { PaymentHistory, SortOption } from './types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';

// ===== Props 타입 =====
interface PaymentHistoryClientProps {
  initialData: PaymentHistory[];
  initialPagination: {
    currentPage: number;
    lastPage: number;
    perPage: number;
    total: number;
  };
}

export function PaymentHistoryClient({
  initialData,
  initialPagination,
}: PaymentHistoryClientProps) {
  // ===== 상태 관리 =====
  const [, _setSortOption] = useState<SortOption>('latest');
  const itemsPerPage = initialPagination.perPage;

  // 거래명세서 팝업 상태
  const [showInvoiceDialog, setShowInvoiceDialog] = useState(false);
  const [, setSelectedPaymentId] = useState<string | null>(null);

  // ===== 거래명세서 버튼 클릭 =====
  const handleViewInvoice = useCallback((paymentId: string) => {
    setSelectedPaymentId(paymentId);
    setShowInvoiceDialog(true);
  }, []);

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<PaymentHistory> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '결제내역',
      description: '결제 내역을 확인합니다',
      icon: Receipt,
      basePath: '/settings/payment-history',

      // ID 추출
      idField: 'id',

      // API 액션 (서버 사이드 페이지네이션)
      actions: {
        getList: async (params?: ListParams) => {
          try {
            const result = await getPayments({
              page: params?.page || 1,
              perPage: itemsPerPage,
            });

            if (result.success) {
              return {
                success: true,
                data: result.data,
                totalCount: result.pagination.total,
                totalPages: result.pagination.lastPage,
              };
            }
            return { success: false, error: '데이터 로드 중 오류가 발생했습니다.' };
          } catch (error) {
            if (isNextRedirectError(error)) throw error;
            return { success: false, error: '데이터 로드 중 오류가 발생했습니다.' };
          }
        },
      },

      // 테이블 컬럼
      columns: [
        { key: 'paymentDate', label: '결제일', copyable: true },
        { key: 'subscriptionName', label: '구독명', copyable: true },
        { key: 'paymentMethod', label: '결제 수단', copyable: true },
        { key: 'subscriptionPeriod', label: '구독 기간', copyable: true },
        { key: 'amount', label: '금액', className: 'text-right', copyable: true },
        { key: 'invoice', label: '거래명세서', className: 'text-center' },
      ],

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

      // 검색 숨김
      hideSearch: true,

      // 체크박스/번호 숨김
      showCheckbox: false,
      showRowNumber: false,

      // 테이블 행 렌더링
      renderTableRow: (
        item: PaymentHistory,
        index: number,
        _globalIndex: number,
        _handlers: SelectionHandlers & RowClickHandlers<PaymentHistory>
      ) => {
        const isLatest = index === 0;

        return (
          <TableRow
            key={item.id}
            className="hover:bg-muted/50"
          >
            {/* 결제일 */}
            <TableCell>{item.paymentDate}</TableCell>
            {/* 구독명 */}
            <TableCell>{item.subscriptionName}</TableCell>
            {/* 결제 수단 */}
            <TableCell>{item.paymentMethod}</TableCell>
            {/* 구독 기간 */}
            <TableCell>
              {item.subscriptionPeriod.start && item.subscriptionPeriod.end
                ? `${item.subscriptionPeriod.start} ~ ${item.subscriptionPeriod.end}`
                : '-'}
            </TableCell>
            {/* 금액 */}
            <TableCell className="text-right font-medium">
              {formatNumber(item.amount)}원
            </TableCell>
            {/* 거래명세서 */}
            <TableCell className="text-center">
              {item.canViewInvoice ? (
                <Button
                  size="sm"
                  variant={isLatest ? 'default' : 'secondary'}
                  className={isLatest ? 'bg-emerald-600 hover:bg-emerald-700' : ''}
                  onClick={() => handleViewInvoice(item.id)}
                >
                  <FileText className="h-4 w-4 mr-1" />
                  거래명세서
                </Button>
              ) : (
                <span className="text-muted-foreground text-sm">-</span>
              )}
            </TableCell>
          </TableRow>
        );
      },

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: PaymentHistory,
        index: number,
        globalIndex: number,
        _handlers: SelectionHandlers & RowClickHandlers<PaymentHistory>
      ) => {
        const isLatest = globalIndex === 1;

        return (
          <ListMobileCard
            key={item.id}
            id={item.id}
            title={`${item.subscriptionName} - ${item.paymentDate}`}
            showCheckbox={false}
            isSelected={false}
            onToggleSelection={() => {}}
            infoGrid={
              <div className="space-y-1.5 text-sm">
                {[
                  { label: '결제일', value: item.paymentDate },
                  { label: '구독명', value: item.subscriptionName },
                  { label: '결제 수단', value: item.paymentMethod || '-' },
                  { label: '금액', value: `${formatNumber(item.amount)}원` },
                  { label: '구독 기간', value: item.subscriptionPeriod.start && item.subscriptionPeriod.end
                    ? `${item.subscriptionPeriod.start} ~ ${item.subscriptionPeriod.end}`
                    : '-' },
                ].map((field) => (
                  <div key={field.label} className="flex justify-between items-center">
                    <span className="text-muted-foreground">{field.label}</span>
                    <span className="font-medium">{field.value}</span>
                  </div>
                ))}
              </div>
            }
            actions={
              item.canViewInvoice ? (
                <Button
                  size="sm"
                  variant={isLatest ? 'default' : 'secondary'}
                  className={isLatest ? 'bg-emerald-600 hover:bg-emerald-700' : ''}
                  onClick={() => handleViewInvoice(item.id)}
                >
                  <FileText className="h-4 w-4 mr-1" />
                  거래명세서
                </Button>
              ) : null
            }
          />
        );
      },
    }),
    [itemsPerPage, handleViewInvoice]
  );

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

      {/* ===== 거래명세서 안내 다이얼로그 ===== */}
      <Dialog open={showInvoiceDialog} onOpenChange={setShowInvoiceDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <FileText className="h-5 w-5 text-blue-500" />
              거래명세서
            </DialogTitle>
            <DialogDescription className="text-left pt-2">
              MES 시스템의 문서 페이지에서 거래명세서를 확인할 수 있습니다.
              <br />
              <br />
              해당 기능은 MES 모듈에서 제공되며, 추후 연동 예정입니다.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button onClick={() => setShowInvoiceDialog(false)}>
              확인
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
