'use client';

/**
 * 상품권 관리
 *
 * 기획서 기준:
 * - 통계 4개: 전체 상품권, 보유 상품권, 사용 상품권, 접대비 해당
 * - 테이블: 체크박스, 번호, 일련번호, 상품권명, 액면가, 구입일, 사용일, 접대비, 상태
 * - 필터: 기간(프리셋), 상태, 접대비
 * - 액션: 상품권 등록
 */

import { useState, useMemo, useCallback, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
  Gift, PlusCircle,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { TableRow, TableCell } from '@/components/ui/table';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { MobileCard } from '@/components/organisms/MobileCard';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type StatCard,
} from '@/components/templates/UniversalListPage';
import {
  STATUS_OPTIONS,
  STATUS_MAP,
  ENTERTAINMENT_FILTER_OPTIONS,
} from './types';
import type {
  GiftCertificateRecord,
} from './types';
import {
  getGiftCertificates,
  getGiftCertificateSummary,
  deleteGiftCertificate,
} from './actions';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { invalidateDashboard } from '@/lib/dashboard-invalidation';
import { formatNumber as formatAmount } from '@/lib/utils/amount';
import { applyFilters, enumFilter } from '@/lib/utils/search';
import { useDateRange } from '@/hooks';

// ===== 테이블 컬럼 정의 (체크박스/No. 제외) =====
const tableColumns = [
  { key: 'rowNumber', label: '번호', className: 'text-center' },
  { key: 'serialNumber', label: '일련번호', sortable: true, copyable: true },
  { key: 'name', label: '상품권명', sortable: true, copyable: true },
  { key: 'faceValue', label: '액면가', className: 'text-right', sortable: true, copyable: true },
  { key: 'purchaseDate', label: '구입일', className: 'text-center', sortable: true, copyable: true },
  { key: 'usedDate', label: '사용일', className: 'text-center', sortable: true, copyable: true },
  { key: 'entertainmentExpense', label: '접대비', className: 'text-center', sortable: true, copyable: true },
  { key: 'status', label: '상태', className: 'text-center', sortable: true },
];

// ===== 기본 Summary =====
const DEFAULT_SUMMARY = {
  totalCount: 0,
  totalAmount: 0,
  holdingCount: 0,
  holdingAmount: 0,
  usedCount: 0,
  usedAmount: 0,
  entertainmentCount: 0,
  entertainmentAmount: 0,
};

export function GiftCertificateManagement() {
  const router = useRouter();

  // ===== 데이터 상태 =====
  const [data, setData] = useState<GiftCertificateRecord[]>([]);
  const [summary, setSummary] = useState(DEFAULT_SUMMARY);
  const [isLoading, setIsLoading] = useState(true);

  // 필터 상태
  const [statusFilter, setStatusFilter] = useState('all');
  const [entertainmentFilter, setEntertainmentFilter] = useState('all');
  const [, setSearchQuery] = useState('');

  // 날짜 범위
  const { startDate, endDate, setStartDate, setEndDate } = useDateRange('currentMonth');

  // ===== 데이터 로드 =====
  const loadData = useCallback(async () => {
    setIsLoading(true);
    try {
      const [listResult, summaryResult] = await Promise.all([
        getGiftCertificates({
          startDate,
          endDate,
          status: statusFilter !== 'all' ? statusFilter : undefined,
        }),
        getGiftCertificateSummary({ startDate, endDate }),
      ]);

      if (listResult.success) {
        setData(listResult.data ?? []);
      }
      if (summaryResult.success && summaryResult.data) {
        setSummary(summaryResult.data);
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('[GiftCertificateManagement] loadData error:', error);
    } finally {
      setIsLoading(false);
    }
  }, [startDate, endDate, statusFilter]);

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

  // ===== 핸들러 =====
  const handleRowClick = useCallback((item: GiftCertificateRecord) => {
    router.push(`/accounting/gift-certificates?mode=view&id=${item.id}`);
  }, [router]);

  const handleCreate = useCallback(() => {
    router.push('/accounting/gift-certificates?mode=new');
  }, [router]);

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<GiftCertificateRecord> = useMemo(
    () => ({
      title: '상품권 관리',
      description: '상품권을 등록하고 관리합니다.',
      icon: Gift,
      basePath: '/accounting/gift-certificates',
      idField: 'id',

      actions: {
        getList: async () => ({
          success: true,
          data,
          totalCount: data.length,
        }),
        deleteItem: async (id: string) => {
          const result = await deleteGiftCertificate(id);
          if (result.success) {
            invalidateDashboard('giftCertificate');
            await loadData();
          }
          return { success: result.success, error: result.error };
        },
      },

      columns: tableColumns,
      clientSideFiltering: true,
      itemsPerPage: 20,
      showCheckbox: true,

      // 검색
      searchPlaceholder: '상품권명, 일련번호 검색...',
      onSearchChange: setSearchQuery,
      searchFilter: (item: GiftCertificateRecord, search: string) => {
        const s = search.toLowerCase();
        return (
          item.name.toLowerCase().includes(s) ||
          item.serialNumber.toLowerCase().includes(s)
        );
      },

      // 날짜 범위 (이번달~D-5달 프리셋)
      dateRangeSelector: {
        enabled: true,
        showPresets: true,
        presets: ['thisMonth', 'lastMonth', 'twoMonthsAgo', 'threeMonthsAgo', 'fourMonthsAgo', 'fiveMonthsAgo'],
        presetLabels: {
          thisMonth: '이번달',
          lastMonth: '지난달',
          twoMonthsAgo: 'D-2달',
          threeMonthsAgo: 'D-3달',
          fourMonthsAgo: 'D-4달',
          fiveMonthsAgo: 'D-5달',
        },
        startDate,
        endDate,
        onStartDateChange: setStartDate,
        onEndDateChange: setEndDate,
      },

      // 헤더 액션: 상품권 등록
      headerActions: () => (
        <Button size="sm" onClick={handleCreate}>
          <PlusCircle className="h-4 w-4 mr-1" />
          상품권 등록
        </Button>
      ),

      // 테이블 헤더 액션: 총 N건 + 상태 필터 + 접대비 필터
      tableHeaderActions: () => (
        <div className="flex items-center gap-2 flex-wrap">
          <span className="text-sm text-muted-foreground whitespace-nowrap">
            총 {data.length}건
          </span>

          {/* 상태 필터 */}
          <Select
            value={statusFilter}
            onValueChange={setStatusFilter}
          >
            <SelectTrigger className="min-w-[120px] w-auto">
              <SelectValue placeholder="상태" />
            </SelectTrigger>
            <SelectContent>
              {STATUS_OPTIONS.map((opt) => (
                <SelectItem key={opt.value} value={opt.value}>
                  {opt.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          {/* 접대비 필터 */}
          <Select
            value={entertainmentFilter}
            onValueChange={setEntertainmentFilter}
          >
            <SelectTrigger className="min-w-[130px] w-auto">
              <SelectValue placeholder="접대비" />
            </SelectTrigger>
            <SelectContent>
              {ENTERTAINMENT_FILTER_OPTIONS.map((opt) => (
                <SelectItem key={opt.value} value={opt.value}>
                  {opt.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      ),

      // 클라이언트 사이드 커스텀 필터 (상태 + 접대비)
      customFilterFn: (items) => {
        return applyFilters(items, [
          enumFilter('status', statusFilter),
          enumFilter('entertainmentExpense', entertainmentFilter),
        ]);
      },

      // 통계 카드 4개 (기획서: 전체 상품권, 보유 상품권, 사용 상품권, 접대비 해당)
      computeStats: (): StatCard[] => [
        {
          label: '전체 상품권',
          value: `${summary.totalCount}건 / ${formatAmount(summary.totalAmount)}원`,
          icon: Gift,
          iconColor: 'text-blue-600',
        },
        {
          label: '보유 상품권',
          value: `${summary.holdingCount}건 / ${formatAmount(summary.holdingAmount)}원`,
          icon: Gift,
          iconColor: 'text-green-600',
        },
        {
          label: '사용 상품권',
          value: `${summary.usedCount}건 / ${formatAmount(summary.usedAmount)}원`,
          icon: Gift,
          iconColor: 'text-orange-600',
        },
        {
          label: '접대비 해당',
          value: `${summary.entertainmentCount}건 / ${formatAmount(summary.entertainmentAmount)}원`,
          icon: Gift,
          iconColor: 'text-purple-600',
        },
      ],

      // 테이블 행 렌더링
      renderTableRow: (
        item: GiftCertificateRecord,
        _index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<GiftCertificateRecord>
      ) => {
        const statusInfo = STATUS_MAP[item.status];

        return (
          <TableRow
            key={item.id}
            className="cursor-pointer hover:bg-muted/50"
            onClick={() => handleRowClick(item)}
          >
            {/* 체크박스 */}
            <TableCell className="text-center w-[40px]" onClick={(e) => e.stopPropagation()}>
              <Checkbox
                checked={handlers.isSelected}
                onCheckedChange={() => handlers.onToggle()}
              />
            </TableCell>
            {/* 번호 */}
            <TableCell className="text-center">{globalIndex}</TableCell>
            {/* 일련번호 */}
            <TableCell>{item.serialNumber}</TableCell>
            {/* 상품권명 */}
            <TableCell className="font-medium">{item.name}</TableCell>
            {/* 액면가 */}
            <TableCell className="text-right">
              {formatAmount(item.faceValue)}
            </TableCell>
            {/* 구입일 */}
            <TableCell className="text-center">{item.purchaseDate}</TableCell>
            {/* 사용일 */}
            <TableCell className="text-center">{item.usedDate || '-'}</TableCell>
            {/* 접대비 */}
            <TableCell className="text-center">
              {item.entertainmentExpense === 'applicable' ? '해당' : '-'}
            </TableCell>
            {/* 상태 */}
            <TableCell className="text-center">
              <span
                className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${statusInfo.color}`}
              >
                {statusInfo.label}
              </span>
            </TableCell>
          </TableRow>
        );
      },

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: GiftCertificateRecord,
        _index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<GiftCertificateRecord>
      ) => {
        const statusInfo = STATUS_MAP[item.status];

        return (
          <MobileCard
            key={item.id}
            id={item.id}
            isSelected={handlers.isSelected}
            onToggle={handlers.onToggle}
            onClick={() => handleRowClick(item)}
            title={`${globalIndex}. ${item.name}`}
            badge={{
              label: statusInfo.label,
              variant: item.status === 'holding'
                ? 'default'
                : item.status === 'used'
                  ? 'secondary'
                  : 'destructive',
            }}
            infoGrid={
              <div className="grid grid-cols-2 gap-x-4 gap-y-2 text-sm">
                <div><span className="text-muted-foreground">상품권번호</span> <span>{item.serialNumber}</span></div>
                <div><span className="text-muted-foreground">액면가</span> <span>{formatAmount(item.faceValue)}원</span></div>
                <div><span className="text-muted-foreground">구입일</span> <span>{item.purchaseDate}</span></div>
                <div><span className="text-muted-foreground">사용일</span> <span>{item.usedDate || '-'}</span></div>
                <div><span className="text-muted-foreground">접대비</span> <span>{item.entertainmentExpense === 'applicable' ? '해당' : '-'}</span></div>
              </div>
            }
          />
        );
      },
    }),
    [data, summary, startDate, endDate, statusFilter, entertainmentFilter, handleRowClick, handleCreate, loadData]
  );

  return (
    <UniversalListPage
      config={config}
      initialData={data}
      initialTotalCount={data.length}
      externalIsLoading={isLoading}
    />
  );
}
