'use client';

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { format, subDays } from 'date-fns';
import {
  Building2,
  Pencil,
  RefreshCw,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { TableRow, TableCell } from '@/components/ui/table';
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 {
  BankTransaction,
  SortOption,
} from './types';
import {
  TRANSACTION_KIND_LABELS,
  DEPOSIT_TYPE_LABELS,
  WITHDRAWAL_TYPE_LABELS,
  SORT_OPTIONS,
  TRANSACTION_TYPE_FILTER_OPTIONS,
} from './types';

// ===== Mock 데이터 생성 =====
const generateMockData = (): BankTransaction[] => {
  const banks = ['국민은행', '신한은행', '우리은행', '하나은행', 'NH농협'];
  const accounts = ['영업계좌', '운영계좌', '급여계좌', '예비계좌'];
  const vendors = ['(주)삼성전자', '현대자동차', 'LG전자', 'SK하이닉스', '네이버'];
  const depositors = ['홍길동', '김철수', '이영희', '박민수', '최지영'];
  const depositTypes = ['unset', 'salesRevenue', 'advance', 'suspense', 'interestIncome'];
  const withdrawalTypes = ['unset', 'purchasePayment', 'salary', 'rent', 'utilities'];

  let runningBalance = 50000000; // 초기 잔액 5천만원

  return Array.from({ length: 50 }, (_, i) => {
    const isDeposit = i % 2 === 0;
    const amount = (Math.floor(Math.random() * 10) + 1) * 100000;

    if (isDeposit) {
      runningBalance += amount;
    } else {
      runningBalance -= amount;
    }

    return {
      id: `txn-${i + 1}`,
      bankName: banks[i % banks.length],
      accountName: accounts[i % accounts.length],
      transactionDate: format(subDays(new Date(), i % 30), 'yyyy-MM-dd HH:mm'),
      type: isDeposit ? 'deposit' : 'withdrawal',
      note: i % 3 === 0 ? '거래 메모' : '',
      vendorId: `vendor-${i % vendors.length}`,
      vendorName: i % 4 === 0 ? '' : vendors[i % vendors.length],
      depositorName: depositors[i % depositors.length],
      depositAmount: isDeposit ? amount : 0,
      withdrawalAmount: isDeposit ? 0 : amount,
      balance: runningBalance,
      transactionType: isDeposit
        ? depositTypes[i % depositTypes.length]
        : withdrawalTypes[i % withdrawalTypes.length],
      sourceId: isDeposit ? `deposit-${i + 1}` : `withdrawal-${i + 1}`,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
  });
};

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

  // ===== 상태 관리 =====
  const [searchQuery, setSearchQuery] = useState('');
  const [sortOption, setSortOption] = useState<SortOption>('latest');
  const [accountFilter, setAccountFilter] = useState<string>('all'); // 결제계좌 필터
  const [transactionTypeFilter, setTransactionTypeFilter] = useState<string>('all'); // 입출금유형 필터
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  // 날짜 범위 상태
  const [startDate, setStartDate] = useState('2025-09-01');
  const [endDate, setEndDate] = useState('2025-09-03');

  // Mock 데이터
  const [data] = useState<BankTransaction[]>(generateMockData);

  // ===== 체크박스 핸들러 =====
  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 accountOptions = useMemo(() => {
    const uniqueAccounts = [...new Set(data.map(d => `${d.bankName}|${d.accountName}`))];
    return [
      { value: 'all', label: '전체' },
      ...uniqueAccounts.map(acc => ({ value: acc, label: acc }))
    ];
  }, [data]);

  // ===== 필터링된 데이터 =====
  const filteredData = useMemo(() => {
    let result = data.filter(item =>
      item.bankName.includes(searchQuery) ||
      item.accountName.includes(searchQuery) ||
      item.vendorName?.includes(searchQuery) ||
      item.depositorName?.includes(searchQuery) ||
      item.note?.includes(searchQuery)
    );

    // 결제계좌 필터
    if (accountFilter !== 'all') {
      const [bank, account] = accountFilter.split('|');
      result = result.filter(item => item.bankName === bank && item.accountName === account);
    }

    // 입출금유형 필터
    if (transactionTypeFilter !== 'all') {
      result = result.filter(item => item.transactionType === transactionTypeFilter);
    }

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

    return result;
  }, [data, searchQuery, accountFilter, transactionTypeFilter, 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 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 handleEditClick = useCallback((item: BankTransaction) => {
    if (item.type === 'deposit') {
      router.push(`/ko/accounting/deposits/${item.sourceId}?mode=edit`);
    } else {
      router.push(`/ko/accounting/withdrawals/${item.sourceId}?mode=edit`);
    }
  }, [router]);

  // 새로고침 핸들러
  const handleRefresh = useCallback(() => {
    console.log('새로고침: 은행 계좌 입출금 내역 최신 데이터 조회');
    // TODO: API 호출로 최신 데이터 조회
  }, []);

  // ===== 통계 카드 =====
  const statCards: StatCard[] = useMemo(() => {
    const totalDeposit = data
      .filter(d => d.type === 'deposit')
      .reduce((sum, d) => sum + d.depositAmount, 0);

    const totalWithdrawal = data
      .filter(d => d.type === 'withdrawal')
      .reduce((sum, d) => sum + d.withdrawalAmount, 0);

    const depositUnsetCount = data.filter(d => d.type === 'deposit' && d.transactionType === 'unset').length;
    const withdrawalUnsetCount = data.filter(d => d.type === 'withdrawal' && d.transactionType === 'unset').length;

    return [
      { label: '입금', value: `${totalDeposit.toLocaleString()}원`, icon: Building2, iconColor: 'text-blue-500' },
      { label: '출금', value: `${totalWithdrawal.toLocaleString()}원`, icon: Building2, iconColor: 'text-red-500' },
      { label: '입금 유형 미설정', value: `${depositUnsetCount}건`, icon: Building2, iconColor: 'text-green-500' },
      { label: '출금 유형 미설정', value: `${withdrawalUnsetCount}건`, icon: Building2, iconColor: 'text-orange-500' },
    ];
  }, [data]);

  // ===== 테이블 컬럼 (14개) =====
  const tableColumns: TableColumn[] = useMemo(() => [
    { key: 'bankName', label: '은행명' },
    { key: 'accountName', label: '계좌명' },
    { key: 'transactionDate', label: '거래일시' },
    { key: 'type', label: '구분', className: 'text-center' },
    { key: 'note', label: '적요' },
    { key: 'vendorName', label: '거래처' },
    { key: 'depositorName', label: '입금자/수취인' },
    { key: 'depositAmount', label: '입금', className: 'text-right' },
    { key: 'withdrawalAmount', label: '출금', className: 'text-right' },
    { key: 'balance', label: '잔액', className: 'text-right' },
    { key: 'transactionType', label: '입출금 유형', className: 'text-center' },
    { key: 'actions', label: '작업', className: 'text-center w-[80px]' },
  ], []);

  // ===== 유형 라벨 가져오기 =====
  const getTransactionTypeLabel = useCallback((item: BankTransaction) => {
    if (!item.transactionType) return '미설정';
    if (item.type === 'deposit') {
      return DEPOSIT_TYPE_LABELS[item.transactionType as keyof typeof DEPOSIT_TYPE_LABELS] || item.transactionType;
    }
    return WITHDRAWAL_TYPE_LABELS[item.transactionType as keyof typeof WITHDRAWAL_TYPE_LABELS] || item.transactionType;
  }, []);

  // ===== 테이블 행 렌더링 =====
  const renderTableRow = useCallback((item: BankTransaction, index: number, globalIndex: number) => {
    const isSelected = selectedItems.has(item.id);
    const isTypeUnset = item.transactionType === 'unset';

    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 className="text-center">{globalIndex}</TableCell>
        {/* 은행명 */}
        <TableCell>{item.bankName}</TableCell>
        {/* 계좌명 */}
        <TableCell>{item.accountName}</TableCell>
        {/* 거래일시 */}
        <TableCell>{item.transactionDate}</TableCell>
        {/* 구분 */}
        <TableCell className="text-center">
          <Badge
            variant="outline"
            className={item.type === 'deposit'
              ? 'border-blue-300 text-blue-600 bg-blue-50'
              : 'border-red-300 text-red-600 bg-red-50'
            }
          >
            {TRANSACTION_KIND_LABELS[item.type]}
          </Badge>
        </TableCell>
        {/* 적요 */}
        <TableCell className="text-gray-500">{item.note || '-'}</TableCell>
        {/* 거래처 */}
        <TableCell>{item.vendorName || '-'}</TableCell>
        {/* 입금자/수취인 */}
        <TableCell>{item.depositorName || '-'}</TableCell>
        {/* 입금 */}
        <TableCell className="text-right font-medium text-blue-600">
          {item.depositAmount > 0 ? item.depositAmount.toLocaleString() : '-'}
        </TableCell>
        {/* 출금 */}
        <TableCell className="text-right font-medium text-red-600">
          {item.withdrawalAmount > 0 ? item.withdrawalAmount.toLocaleString() : '-'}
        </TableCell>
        {/* 잔액 */}
        <TableCell className="text-right font-medium">
          {item.balance.toLocaleString()}
        </TableCell>
        {/* 입출금 유형 */}
        <TableCell className="text-center">
          <Badge
            variant="outline"
            className={isTypeUnset ? 'border-red-300 text-red-500 bg-red-50' : ''}
          >
            {getTransactionTypeLabel(item)}
          </Badge>
        </TableCell>
        {/* 작업 */}
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          {isSelected && (
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8 text-gray-600 hover:text-gray-700 hover:bg-gray-50"
              onClick={() => handleEditClick(item)}
            >
              <Pencil className="h-4 w-4" />
            </Button>
          )}
        </TableCell>
      </TableRow>
    );
  }, [selectedItems, toggleSelection, handleEditClick, getTransactionTypeLabel]);

  // ===== 모바일 카드 렌더링 =====
  const renderMobileCard = useCallback((
    item: BankTransaction,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => {
    return (
      <ListMobileCard
        id={item.id}
        title={`${item.bankName} - ${item.accountName}`}
        headerBadges={
          <>
            <Badge
              variant="outline"
              className={item.type === 'deposit'
                ? 'border-blue-300 text-blue-600 bg-blue-50'
                : 'border-red-300 text-red-600 bg-red-50'
              }
            >
              {TRANSACTION_KIND_LABELS[item.type]}
            </Badge>
            <Badge variant="outline">
              {getTransactionTypeLabel(item)}
            </Badge>
          </>
        }
        isSelected={isSelected}
        onToggleSelection={onToggle}
        infoGrid={
          <div className="grid grid-cols-2 gap-3">
            <InfoField label="거래일시" value={item.transactionDate} />
            <InfoField label="거래처" value={item.vendorName || '-'} />
            <InfoField
              label="입금"
              value={item.depositAmount > 0 ? `${item.depositAmount.toLocaleString()}원` : '-'}
            />
            <InfoField
              label="출금"
              value={item.withdrawalAmount > 0 ? `${item.withdrawalAmount.toLocaleString()}원` : '-'}
            />
            <InfoField label="잔액" value={`${item.balance.toLocaleString()}원`} />
            <InfoField label="입금자/수취인" value={item.depositorName || '-'} />
          </div>
        }
        actions={
          isSelected ? (
            <Button variant="outline" className="w-full" onClick={() => handleEditClick(item)}>
              <Pencil className="w-4 h-4 mr-2" /> 수정
            </Button>
          ) : undefined
        }
      />
    );
  }, [handleEditClick, getTransactionTypeLabel]);

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

  // ===== 테이블 상단 새로고침 버튼 (출금관리 스타일) =====
  const beforeTableContent = (
    <div className="flex items-center justify-end w-full">
      <Button
        variant="outline"
        onClick={handleRefresh}
      >
        <RefreshCw className="h-4 w-4 mr-2" />
        새로고침
      </Button>
    </div>
  );

  // ===== 테이블 헤더 액션 (3개 필터) =====
  const tableHeaderActions = (
    <div className="flex items-center gap-2 flex-wrap">
      {/* 결제계좌 필터 */}
      <Select value={accountFilter} onValueChange={setAccountFilter}>
        <SelectTrigger className="w-[180px]">
          <SelectValue placeholder="결제계좌" />
        </SelectTrigger>
        <SelectContent>
          {accountOptions.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      {/* 입출금유형 필터 */}
      <Select value={transactionTypeFilter} onValueChange={setTransactionTypeFilter}>
        <SelectTrigger className="w-[130px]">
          <SelectValue placeholder="입출금유형" />
        </SelectTrigger>
        <SelectContent>
          {TRANSACTION_TYPE_FILTER_OPTIONS.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 tableTotals = useMemo(() => {
    const totalDeposit = filteredData.reduce((sum, item) => sum + item.depositAmount, 0);
    const totalWithdrawal = filteredData.reduce((sum, item) => sum + item.withdrawalAmount, 0);
    return { totalDeposit, totalWithdrawal };
  }, [filteredData]);

  // ===== 테이블 하단 합계 행 =====
  const tableFooter = (
    <TableRow className="bg-muted/50 font-medium">
      <TableCell className="text-center"></TableCell>
      <TableCell className="font-bold">합계</TableCell>
      <TableCell></TableCell>
      <TableCell></TableCell>
      <TableCell></TableCell>
      <TableCell></TableCell>
      <TableCell></TableCell>
      <TableCell></TableCell>
      <TableCell></TableCell>
      <TableCell className="text-right font-bold text-blue-600">
        {tableTotals.totalDeposit.toLocaleString()}
      </TableCell>
      <TableCell className="text-right font-bold text-red-600">
        {tableTotals.totalWithdrawal.toLocaleString()}
      </TableCell>
      <TableCell></TableCell>
      <TableCell></TableCell>
      <TableCell></TableCell>
    </TableRow>
  );

  return (
    <IntegratedListTemplateV2
      title="입출금 계좌조회"
      description="은행 계좌 정보와 입출금 내역을 조회할 수 있습니다"
      icon={Building2}
      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: BankTransaction) => item.id}
      renderTableRow={renderTableRow}
      renderMobileCard={renderMobileCard}
      pagination={{
        currentPage,
        totalPages,
        totalItems: filteredData.length,
        itemsPerPage,
        onPageChange: setCurrentPage,
      }}
    />
  );
}