'use client';

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 TableColumn,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard } from '@/components/organisms/MobileCard';
import { formatNumber } from '@/lib/utils/amount';
import type { PaymentHistory, SortOption } from './types';

interface PaymentHistoryManagementProps {
  initialData: PaymentHistory[];
  initialPagination: {
    currentPage: number;
    lastPage: number;
    perPage: number;
    total: number;
  };
}

export function PaymentHistoryManagement({
  initialData,
  initialPagination,
}: PaymentHistoryManagementProps) {
  // ===== 상태 관리 =====
  const [searchQuery, _setSearchQuery] = useState('');
  const [sortOption, _setSortOption] = useState<SortOption>('latest');
  const [currentPage, setCurrentPage] = useState(initialPagination.currentPage);
  const itemsPerPage = initialPagination.perPage;

  // API 데이터
  const [data] = useState<PaymentHistory[]>(initialData);

  // 거래명세서 팝업 상태
  const [showInvoiceDialog, setShowInvoiceDialog] = useState(false);

  // ===== 필터링된 데이터 =====
  const filteredData = useMemo(() => {
    let result = data.filter(item =>
      item.subscriptionName.includes(searchQuery) ||
      item.paymentMethod.includes(searchQuery) ||
      item.paymentDate.includes(searchQuery)
    );

    // 정렬
    switch (sortOption) {
      case 'latest':
        result.sort((a, b) => new Date(b.paymentDate).getTime() - new Date(a.paymentDate).getTime());
        break;
      case 'oldest':
        result.sort((a, b) => new Date(a.paymentDate).getTime() - new Date(b.paymentDate).getTime());
        break;
      case 'amountHigh':
        result.sort((a, b) => b.amount - a.amount);
        break;
      case 'amountLow':
        result.sort((a, b) => a.amount - b.amount);
        break;
    }

    return result;
  }, [data, searchQuery, sortOption]);

  const _paginatedData = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    return filteredData.slice(startIndex, startIndex + itemsPerPage);
  }, [filteredData, currentPage, itemsPerPage]);

  const totalPages = Math.ceil(filteredData.length / itemsPerPage);

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

  // ===== 테이블 컬럼 =====
  const tableColumns: TableColumn[] = useMemo(() => [
    { 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' },
  ], []);

  // ===== 테이블 행 렌더링 =====
  const renderTableRow = useCallback((
    item: PaymentHistory,
    index: number,
    _globalIndex: number,
    _handlers: { isSelected: boolean; onToggle: () => void; onRowClick?: () => void }
  ) => {
    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}
        </TableCell>
        {/* 금액 */}
        <TableCell className="text-right font-medium">
          {formatNumber(item.amount)}
        </TableCell>
        {/* 거래명세서 */}
        <TableCell className="text-center">
          <Button
            size="sm"
            variant={isLatest ? 'default' : 'secondary'}
            className={isLatest ? 'bg-emerald-600 hover:bg-emerald-700' : ''}
            onClick={handleViewInvoice}
          >
            <FileText className="h-4 w-4 mr-1" />
            거래명세서
          </Button>
        </TableCell>
      </TableRow>
    );
  }, [handleViewInvoice]);

  // ===== 모바일 카드 렌더링 =====
  const renderMobileCard = useCallback((
    item: PaymentHistory,
    index: number,
    globalIndex: number,
    _handlers: { isSelected: boolean; onToggle: () => void; onRowClick?: () => void }
  ) => {
    const isLatest = globalIndex === 1;

    return (
      <ListMobileCard
        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={
          <Button
            size="sm"
            variant={isLatest ? 'default' : 'secondary'}
            className={isLatest ? 'bg-emerald-600 hover:bg-emerald-700' : ''}
            onClick={handleViewInvoice}
          >
            <FileText className="h-4 w-4 mr-1" />
            거래명세서
          </Button>
        }
      />
    );
  }, [handleViewInvoice]);

  // ===== 테이블 헤더 액션 (주석처리: 필요시 활성화) =====
  // const tableHeaderActions = (
  //   <div className="flex items-center gap-2 flex-wrap">
  //     {/* 정렬 */}
  //     <Select value={sortOption} onValueChange={(value) => setSortOption(value as SortOption)}>
  //       <SelectTrigger className="min-w-[120px] w-auto">
  //         <SelectValue placeholder="정렬" />
  //       </SelectTrigger>
  //       <SelectContent>
  //         {SORT_OPTIONS.map((option) => (
  //           <SelectItem key={option.value} value={option.value}>
  //             {option.label}
  //           </SelectItem>
  //         ))}
  //       </SelectContent>
  //     </Select>
  //   </div>
  // );

  // ===== UniversalListPage 설정 =====
  const paymentHistoryConfig: UniversalListConfig<PaymentHistory> = {
    title: '결제내역',
    description: '결제 내역을 확인합니다',
    icon: Receipt,
    basePath: '/payment-history',

    idField: 'id',

    actions: {
      getList: async () => ({
        success: true,
        data: data,
        totalCount: data.length,
      }),
    },

    columns: tableColumns,

    hideSearch: true,
    showCheckbox: false,
    showRowNumber: false,

    itemsPerPage,

    clientSideFiltering: true,

    renderTableRow,
    renderMobileCard,

    renderDialogs: () => (
      <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>
    ),
  };

  return (
    <UniversalListPage<PaymentHistory>
      config={paymentHistoryConfig}
      initialData={filteredData}
      initialTotalCount={filteredData.length}
      externalPagination={{
        currentPage,
        totalPages,
        totalItems: filteredData.length,
        itemsPerPage,
        onPageChange: setCurrentPage,
      }}
    />
  );
}