'use client';

import { useState, useMemo, useCallback, useEffect } from 'react';
import { format, startOfMonth, endOfMonth } from 'date-fns';
import {
  CreditCard,
  RefreshCw,
  Save,
  Loader2,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { TableRow, TableCell } from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  IntegratedListTemplateV2,
  type TableColumn,
  type StatCard,
} from '@/components/templates/IntegratedListTemplateV2';
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import type {
  CardTransaction,
  SortOption,
} from './types';
import {
  SORT_OPTIONS,
  ACCOUNT_SUBJECT_OPTIONS,
} from './types';
import { getCardTransactionList, getCardTransactionSummary, bulkUpdateAccountCode } from './actions';

// ===== Props =====
interface CardTransactionInquiryProps {
  initialData?: CardTransaction[];
  initialSummary?: {
    previousMonthTotal: number;
    currentMonthTotal: number;
  };
  initialPagination?: {
    currentPage: number;
    lastPage: number;
    perPage: number;
    total: number;
  };
}

export function CardTransactionInquiry({
  initialData = [],
  initialSummary,
  initialPagination,
}: CardTransactionInquiryProps) {
  // ===== 상태 관리 =====
  const [searchQuery, setSearchQuery] = useState('');
  const [sortOption, setSortOption] = useState<SortOption>('latest');
  const [cardFilter, setCardFilter] = useState<string>('all'); // 카드명 필터
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(initialPagination?.currentPage || 1);
  const itemsPerPage = 20;
  const [isLoading, setIsLoading] = useState(!initialData.length);

  // 상단 계정과목명 선택 (저장용)
  const [selectedAccountSubject, setSelectedAccountSubject] = useState<string>('unset');

  // 계정과목명 저장 다이얼로그
  const [showSaveDialog, setShowSaveDialog] = useState(false);

  // 선택 필요 알림 다이얼로그
  const [showSelectWarningDialog, setShowSelectWarningDialog] = useState(false);

  // 날짜 범위 상태
  const [startDate, setStartDate] = useState(() => format(startOfMonth(new Date()), 'yyyy-MM-dd'));
  const [endDate, setEndDate] = useState(() => format(endOfMonth(new Date()), 'yyyy-MM-dd'));

  // 데이터 상태
  const [data, setData] = useState<CardTransaction[]>(initialData);
  const [summary, setSummary] = useState(
    initialSummary || { previousMonthTotal: 0, currentMonthTotal: 0 }
  );
  const [pagination, setPagination] = useState(
    initialPagination || { currentPage: 1, lastPage: 1, perPage: 20, total: 0 }
  );

  // ===== 데이터 로드 =====
  const loadData = useCallback(async () => {
    setIsLoading(true);
    try {
      // 정렬 옵션 매핑
      const sortMapping: Record<SortOption, { sortBy: string; sortDir: 'asc' | 'desc' }> = {
        latest: { sortBy: 'used_at', sortDir: 'desc' },
        oldest: { sortBy: 'used_at', sortDir: 'asc' },
        amountHigh: { sortBy: 'amount', sortDir: 'desc' },
        amountLow: { sortBy: 'amount', sortDir: 'asc' },
      };
      const sortParams = sortMapping[sortOption];

      const [listResult, summaryResult] = await Promise.all([
        getCardTransactionList({
          page: currentPage,
          perPage: itemsPerPage,
          startDate,
          endDate,
          search: searchQuery || undefined,
          sortBy: sortParams.sortBy,
          sortDir: sortParams.sortDir,
        }),
        getCardTransactionSummary({ startDate, endDate }),
      ]);

      if (listResult.success) {
        setData(listResult.data);
        setPagination(listResult.pagination);
      }

      if (summaryResult.success && summaryResult.data) {
        setSummary({
          previousMonthTotal: summaryResult.data.previousMonthTotal,
          currentMonthTotal: summaryResult.data.currentMonthTotal,
        });
      }
    } catch (error) {
      console.error('[CardTransactionInquiry] loadData error:', error);
    } finally {
      setIsLoading(false);
    }
  }, [currentPage, startDate, endDate, searchQuery, sortOption]);

  // 데이터 로드 (필터 변경 시)
  useEffect(() => {
    loadData();
  }, [loadData]);

  // ===== 체크박스 핸들러 =====
  const toggleSelection = useCallback((id: string) => {
    setSelectedItems(prev => {
      const newSet = new Set(prev);
      if (newSet.has(id)) newSet.delete(id);
      else newSet.add(id);
      return newSet;
    });
  }, []);

  // ===== 카드명 옵션 =====
  const cardOptions = useMemo(() => {
    const uniqueCards = [...new Set(data.map(d => d.cardName))];
    return [
      { value: 'all', label: '전체' },
      ...uniqueCards.map(card => ({ value: card, label: card }))
    ];
  }, [data]);

  // ===== 필터링된 데이터 =====
  const filteredData = useMemo(() => {
    let result = data.filter(item =>
      item.card.includes(searchQuery) ||
      item.cardName.includes(searchQuery) ||
      item.user.includes(searchQuery) ||
      item.merchantName.includes(searchQuery)
    );

    // 카드명 필터
    if (cardFilter !== 'all') {
      result = result.filter(item => item.cardName === cardFilter);
    }

    // 정렬
    switch (sortOption) {
      case 'latest':
        result.sort((a, b) => new Date(b.usedAt).getTime() - new Date(a.usedAt).getTime());
        break;
      case 'oldest':
        result.sort((a, b) => new Date(a.usedAt).getTime() - new Date(b.usedAt).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, cardFilter, 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 handleRefresh = useCallback(() => {
    loadData();
  }, [loadData]);

  // ===== 전체 선택 핸들러 =====
  const toggleSelectAll = useCallback(() => {
    if (selectedItems.size === filteredData.length && filteredData.length > 0) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(filteredData.map(item => item.id)));
    }
  }, [selectedItems.size, filteredData]);

  // ===== 계정과목명 저장 핸들러 =====
  const handleSaveAccountSubject = useCallback(() => {
    if (selectedItems.size === 0) {
      setShowSelectWarningDialog(true);
      return;
    }
    setShowSaveDialog(true);
  }, [selectedItems.size]);

  // 계정과목명 저장 확정
  const [isSaving, setIsSaving] = useState(false);

  const handleConfirmSaveAccountSubject = useCallback(async () => {
    if (selectedAccountSubject === 'unset') return;

    setIsSaving(true);
    try {
      const ids = Array.from(selectedItems).map(id => parseInt(id, 10));
      const result = await bulkUpdateAccountCode(ids, selectedAccountSubject);

      if (result.success) {
        // 성공 시 데이터 새로고침
        await loadData();
        setSelectedItems(new Set());
        setSelectedAccountSubject('unset');
      } else {
        console.error('[CardTransactionInquiry] bulkUpdate error:', result.error);
      }
    } catch (error) {
      console.error('[CardTransactionInquiry] bulkUpdate error:', error);
    } finally {
      setIsSaving(false);
      setShowSaveDialog(false);
    }
  }, [selectedAccountSubject, selectedItems, loadData]);

  // ===== 통계 카드 (전월/당월 사용액) =====
  const statCards: StatCard[] = useMemo(() => {
    return [
      { label: '전월 사용액', value: `${summary.previousMonthTotal.toLocaleString()}원`, icon: CreditCard, iconColor: 'text-gray-500' },
      { label: '당월 사용액', value: `${summary.currentMonthTotal.toLocaleString()}원`, icon: CreditCard, iconColor: 'text-blue-500' },
    ];
  }, [summary]);

  // ===== 테이블 컬럼 (체크박스/번호 없음) =====
  const tableColumns: TableColumn[] = useMemo(() => [
    { key: 'card', label: '카드' },
    { key: 'cardName', label: '카드명' },
    { key: 'user', label: '사용자' },
    { key: 'usedAt', label: '사용일시' },
    { key: 'merchantName', label: '가맹점명' },
    { key: 'amount', label: '사용금액', className: 'text-right' },
  ], []);

  // ===== 테이블 행 렌더링 =====
  const renderTableRow = useCallback((item: CardTransaction) => {
    const isSelected = selectedItems.has(item.id);

    return (
      <TableRow
        key={item.id}
        className="hover:bg-muted/50"
      >
        {/* 체크박스 */}
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          <Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(item.id)} />
        </TableCell>
        {/* 카드 */}
        <TableCell>{item.card}</TableCell>
        {/* 카드명 */}
        <TableCell>{item.cardName}</TableCell>
        {/* 사용자 */}
        <TableCell>{item.user}</TableCell>
        {/* 사용일시 */}
        <TableCell>{item.usedAt}</TableCell>
        {/* 가맹점명 */}
        <TableCell>{item.merchantName}</TableCell>
        {/* 사용금액 */}
        <TableCell className="text-right font-medium">
          {item.amount.toLocaleString()}
        </TableCell>
      </TableRow>
    );
  }, [selectedItems, toggleSelection]);

  // ===== 모바일 카드 렌더링 =====
  const renderMobileCard = useCallback((
    item: CardTransaction,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => {
    return (
      <ListMobileCard
        id={item.id}
        title={`${item.card} - ${item.cardName}`}
        isSelected={isSelected}
        onToggleSelection={onToggle}
        showCheckbox={true}
        infoGrid={
          <div className="grid grid-cols-2 gap-3">
            <InfoField label="사용자" value={item.user} />
            <InfoField label="사용일시" value={item.usedAt} />
            <InfoField label="가맹점명" value={item.merchantName} />
            <InfoField label="사용금액" value={`${item.amount.toLocaleString()}원`} />
          </div>
        }
      />
    );
  }, []);

  // ===== 헤더 액션 (날짜 선택만) =====
  const headerActions = (
    <DateRangeSelector
      startDate={startDate}
      endDate={endDate}
      onStartDateChange={setStartDate}
      onEndDateChange={setEndDate}
    />
  );

  // ===== 상단 계정과목명 + 저장 버튼 + 새로고침 =====
  const beforeTableContent = (
    <div className="flex items-center justify-between w-full">
      <div className="flex items-center gap-2">
        <span className="text-sm font-medium text-gray-700">계정과목명</span>
        <Select value={selectedAccountSubject} onValueChange={setSelectedAccountSubject}>
          <SelectTrigger className="w-[150px]">
            <SelectValue placeholder="계정과목명 선택" />
          </SelectTrigger>
          <SelectContent>
            {ACCOUNT_SUBJECT_OPTIONS.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Button onClick={handleSaveAccountSubject} className="bg-orange-500 hover:bg-orange-600">
          <Save className="h-4 w-4 mr-2" />
          저장
        </Button>
      </div>
      <Button
        variant="outline"
        onClick={handleRefresh}
        disabled={isLoading}
      >
        {isLoading ? (
          <Loader2 className="h-4 w-4 mr-2 animate-spin" />
        ) : (
          <RefreshCw className="h-4 w-4 mr-2" />
        )}
        새로고침
      </Button>
    </div>
  );

  // ===== 테이블 헤더 액션 (2개 필터) =====
  const tableHeaderActions = (
    <div className="flex items-center gap-2 flex-wrap">
      {/* 카드명 필터 */}
      <Select value={cardFilter} onValueChange={setCardFilter}>
        <SelectTrigger className="w-[150px]">
          <SelectValue placeholder="카드" />
        </SelectTrigger>
        <SelectContent>
          {cardOptions.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      {/* 정렬 */}
      <Select value={sortOption} onValueChange={(value) => setSortOption(value as SortOption)}>
        <SelectTrigger className="w-[120px]">
          <SelectValue placeholder="정렬" />
        </SelectTrigger>
        <SelectContent>
          {SORT_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );

  // ===== 테이블 합계 계산 =====
  const totalAmount = useMemo(() => {
    return filteredData.reduce((sum, item) => sum + item.amount, 0);
  }, [filteredData]);

  // ===== 테이블 하단 합계 행 =====
  const tableFooter = (
    <TableRow className="bg-muted/50 font-medium">
      <TableCell className="text-center"></TableCell>
      <TableCell colSpan={5} className="text-right font-bold">합계</TableCell>
      <TableCell className="text-right font-bold">
        {totalAmount.toLocaleString()}
      </TableCell>
    </TableRow>
  );

  return (
    <>
      <IntegratedListTemplateV2
        title="카드 내역 조회"
        description="법인카드 사용 내역을 조회합니다"
        icon={CreditCard}
        headerActions={headerActions}
        stats={statCards}
        searchValue={searchQuery}
        onSearchChange={setSearchQuery}
        searchPlaceholder="카드, 카드명, 사용자, 가맹점명 검색..."
        beforeTableContent={beforeTableContent}
        tableHeaderActions={tableHeaderActions}
        tableColumns={tableColumns}
        tableFooter={tableFooter}
        data={paginatedData}
        totalCount={filteredData.length}
        allData={filteredData}
        selectedItems={selectedItems}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        getItemId={(item: CardTransaction) => item.id}
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        showCheckbox={true}
        showRowNumber={false}
        pagination={{
          currentPage,
          totalPages,
          totalItems: filteredData.length,
          itemsPerPage,
          onPageChange: setCurrentPage,
        }}
      />

      {/* 계정과목명 저장 확인 다이얼로그 */}
      <Dialog open={showSaveDialog} onOpenChange={setShowSaveDialog}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>계정과목명 변경</DialogTitle>
            <DialogDescription>
              {selectedItems.size}개의 카드 사용 내역을{' '}
              <span className="font-semibold text-orange-500">
                {ACCOUNT_SUBJECT_OPTIONS.find(o => o.value === selectedAccountSubject)?.label}
              </span>
              (으)로 모두 변경하시겠습니까?
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="gap-2 sm:gap-0">
            <Button variant="outline" onClick={() => setShowSaveDialog(false)} disabled={isSaving}>
              취소
            </Button>
            <Button
              onClick={handleConfirmSaveAccountSubject}
              className="bg-orange-500 hover:bg-orange-600"
              disabled={isSaving}
            >
              {isSaving ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  저장 중...
                </>
              ) : (
                '확인'
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 선택 필요 알림 다이얼로그 */}
      <AlertDialog open={showSelectWarningDialog} onOpenChange={setShowSelectWarningDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>항목 선택 필요</AlertDialogTitle>
            <AlertDialogDescription>
              변경할 카드 사용 내역을 먼저 선택해주세요.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogAction onClick={() => setShowSelectWarningDialog(false)}>
              확인
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}