'use client';

import { useState, useMemo, useCallback, useEffect, useRef } from 'react';
import { format, parseISO, subMonths, startOfMonth, endOfMonth } from 'date-fns';
import { ko } from 'date-fns/locale';
import { Download, FileText, Loader2, Printer, Search } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  TableFooter,
} from '@/components/ui/table';
import { DateRangePicker } from '@/components/ui/date-range-picker';
import { Input } from '@/components/ui/input';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { formatNumber as formatAmount } from '@/lib/utils/amount';
import { printElement } from '@/lib/print-utils';
import type { NoteReceivableItem, DailyAccountItem } from './types';
import { getNoteReceivables, getDailyAccounts, getDailyReportSummary } from './actions';
import { toast } from 'sonner';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { usePermission } from '@/hooks/usePermission';

// ===== 빠른 월 선택 버튼 정의 =====
const QUICK_MONTH_BUTTONS = [
  { label: '이번달', months: 0 },
  { label: '지난달', months: 1 },
  { label: 'D-2월', months: 2 },
  { label: 'D-3월', months: 3 },
  { label: 'D-4월', months: 4 },
  { label: 'D-5월', months: 5 },
] as const;

// ===== Props 인터페이스 =====
interface DailyReportProps {
  initialNoteReceivables?: NoteReceivableItem[];
  initialDailyAccounts?: DailyAccountItem[];
}

export function DailyReport({ initialNoteReceivables = [], initialDailyAccounts = [] }: DailyReportProps) {
  const { canExport } = usePermission();
  // ===== 상태 관리 =====
  const [startDate, setStartDate] = useState(() => format(startOfMonth(new Date()), 'yyyy-MM-dd'));
  const [endDate, setEndDate] = useState(() => format(new Date(), 'yyyy-MM-dd'));
  const [searchTerm, setSearchTerm] = useState('');
  const [noteReceivables, setNoteReceivables] = useState<NoteReceivableItem[]>(initialNoteReceivables);
  const [dailyAccounts, setDailyAccounts] = useState<DailyAccountItem[]>(initialDailyAccounts);
  const [summary, setSummary] = useState<{
    noteReceivableTotal: number;
    foreignCurrencyTotal: number;
    cashAssetTotal: number;
    krwTotals: { carryover: number; income: number; expense: number; balance: number };
    usdTotals: { carryover: number; income: number; expense: number; balance: number };
  } | null>(null);
  const [isLoading, setIsLoading] = useState(!initialNoteReceivables.length);

  // ===== 데이터 로드 =====
  const loadData = useCallback(async () => {
    setIsLoading(true);
    try {
      const [noteResult, accountResult, summaryResult] = await Promise.all([
        getNoteReceivables({ date: startDate }),
        getDailyAccounts({ date: startDate }),
        getDailyReportSummary({ date: startDate }),
      ]);

      if (noteResult.success) {
        setNoteReceivables(noteResult.data);
      }

      if (accountResult.success) {
        setDailyAccounts(accountResult.data);
      }

      if (summaryResult.success && summaryResult.data) {
        setSummary({
          noteReceivableTotal: summaryResult.data.noteReceivableTotal,
          foreignCurrencyTotal: summaryResult.data.foreignCurrencyTotal,
          cashAssetTotal: summaryResult.data.cashAssetTotal,
          krwTotals: summaryResult.data.krwTotals,
          usdTotals: summaryResult.data.usdTotals,
        });
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('Failed to load daily report:', error);
    } finally {
      setIsLoading(false);
    }
  }, [startDate]);

  // ===== 초기 로드 및 날짜 변경시 재로드 =====
  const isInitialMount = useRef(true);
  const prevDateRef = useRef(startDate);

  useEffect(() => {
    // 초기 마운트 또는 날짜가 실제로 변경된 경우에만 로드
    if (isInitialMount.current || prevDateRef.current !== startDate) {
      isInitialMount.current = false;
      prevDateRef.current = startDate;
      loadData();
    }
  }, [startDate, loadData]);

  // ===== 어음 합계 (API 요약 사용) =====
  const noteReceivableTotal = useMemo(() => {
    return summary?.noteReceivableTotal ?? noteReceivables.reduce((sum, item) => sum + item.currentBalance, 0);
  }, [summary, noteReceivables]);

  // ===== 일별 계좌 합계 (API 요약 사용) =====
  const accountTotals = useMemo(() => {
    if (summary) {
      return { krw: summary.krwTotals, usd: summary.usdTotals };
    }

    const krwAccounts = dailyAccounts.filter(item => item.currency === 'KRW');
    const usdAccounts = dailyAccounts.filter(item => item.currency === 'USD');

    const krwTotal = krwAccounts.reduce(
      (acc, item) => ({
        carryover: acc.carryover + item.carryover,
        income: acc.income + item.income,
        expense: acc.expense + item.expense,
        balance: acc.balance + item.balance,
      }),
      { carryover: 0, income: 0, expense: 0, balance: 0 }
    );

    const usdTotal = usdAccounts.reduce(
      (acc, item) => ({
        carryover: acc.carryover + item.carryover,
        income: acc.income + item.income,
        expense: acc.expense + item.expense,
        balance: acc.balance + item.balance,
      }),
      { carryover: 0, income: 0, expense: 0, balance: 0 }
    );

    return { krw: krwTotal, usd: usdTotal };
  }, [summary, dailyAccounts]);

  // ===== 현금성 자산 합계 =====
  const cashAssetTotal = useMemo(() => {
    return {
      carryover: accountTotals.krw.carryover,
      income: accountTotals.krw.income,
      expense: accountTotals.krw.expense,
      balance: accountTotals.krw.balance,
    };
  }, [accountTotals]);

  // ===== 선택된 날짜 정보 =====
  const startDateInfo = useMemo(() => {
    try {
      const date = parseISO(startDate);
      return {
        formatted: format(date, 'yyyy년 M월 d일', { locale: ko }),
        dayOfWeek: format(date, 'EEEE', { locale: ko }),
      };
    } catch {
      return { formatted: '', dayOfWeek: '' };
    }
  }, [startDate]);

  // ===== 엑셀 다운로드 (프록시 API 직접 호출) =====
  const handleExcelDownload = useCallback(async () => {
    try {
      const url = `/api/proxy/daily-report/export?date=${startDate}`;
      const response = await fetch(url);

      if (!response.ok) {
        toast.error(`엑셀 다운로드에 실패했습니다. (${response.status})`);
        return;
      }

      const blob = await response.blob();
      const contentDisposition = response.headers.get('Content-Disposition');
      const filename = contentDisposition?.match(/filename="?(.+)"?/)?.[1] || `일일일보_${startDate}.xlsx`;

      const blobUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = blobUrl;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(blobUrl);
      toast.success('엑셀 파일이 다운로드되었습니다.');
    } catch {
      toast.error('엑셀 다운로드 중 오류가 발생했습니다.');
    }
  }, [startDate]);

  // ===== 빠른 월 선택 =====
  const handleQuickMonth = useCallback((monthsAgo: number) => {
    const target = monthsAgo === 0 ? new Date() : subMonths(new Date(), monthsAgo);
    setStartDate(format(startOfMonth(target), 'yyyy-MM-dd'));
    setEndDate(format(endOfMonth(target), 'yyyy-MM-dd'));
  }, []);

  // ===== 인쇄 =====
  const printAreaRef = useRef<HTMLDivElement>(null);
  const handlePrint = useCallback(() => {
    if (printAreaRef.current) {
      printElement(printAreaRef.current, {
        title: `일일일보_${startDate}`,
        styles: `
          .print-container { font-size: 11px; }
          table { width: 100%; margin-bottom: 12px; }
          h3 { margin-bottom: 8px; }
        `,
      });
    }
  }, [startDate]);

  // ===== USD 금액 포맷 =====
  const formatUsd = useCallback((value: number) => `$ ${formatAmount(value)}`, []);

  // ===== 검색 필터링 =====
  const filteredNoteReceivables = useMemo(() => {
    if (!searchTerm) return noteReceivables;
    const term = searchTerm.toLowerCase();
    return noteReceivables.filter(item =>
      item.content.toLowerCase().includes(term)
    );
  }, [noteReceivables, searchTerm]);

  const filteredDailyAccounts = useMemo(() => {
    if (!searchTerm) return dailyAccounts;
    const term = searchTerm.toLowerCase();
    return dailyAccounts.filter(item =>
      item.category.toLowerCase().includes(term)
    );
  }, [dailyAccounts, searchTerm]);

  // ===== USD 데이터 존재 여부 =====
  const hasUsdAccounts = useMemo(() =>
    filteredDailyAccounts.some(item => item.currency === 'USD'),
    [filteredDailyAccounts]
  );

  return (
    <PageLayout>
      {/* 헤더 */}
      <PageHeader
        title="일일 일보"
        description="일일 자금 현황을 한눈에 확인합니다."
        icon={FileText}
      />

      {/* 헤더 액션 (날짜 선택, 빠른 월 선택, 검색, 인쇄) */}
      <Card>
        <CardContent className="p-3 md:p-4">
          <div className="flex flex-col gap-2 md:gap-3">
            {/* DateRange */}
            <DateRangePicker
              startDate={startDate}
              endDate={endDate}
              onStartDateChange={setStartDate}
              onEndDateChange={setEndDate}
              size="sm"
              className="w-full md:w-auto md:min-w-[280px]"
              displayFormat="yyyy-MM-dd"
            />
            {/* 빠른 월 선택 버튼 - 모바일: 가로 스크롤 */}
            <div className="flex items-center gap-1.5 md:gap-2 overflow-x-auto pb-1 -mb-1">
              {QUICK_MONTH_BUTTONS.map((btn) => (
                <Button
                  key={btn.label}
                  variant="outline"
                  size="sm"
                  className="h-7 md:h-8 px-2 md:px-2.5 text-xs shrink-0"
                  onClick={() => handleQuickMonth(btn.months)}
                >
                  {btn.label}
                </Button>
              ))}
            </div>
            {/* 검색 + 인쇄/엑셀 - 모바일: 세로 배치 */}
            <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:justify-between">
              <div className="relative flex-1 sm:max-w-[300px]">
                <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
                <Input
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  placeholder="검색..."
                  className="pl-8 h-8 text-sm"
                />
              </div>
              <div className="flex items-center gap-2">
                <Button variant="outline" size="sm" onClick={handlePrint} className="h-7 md:h-8 px-2 md:px-3 text-xs">
                  <Printer className="mr-1 h-3.5 w-3.5" />
                  인쇄
                </Button>
                {canExport && (
                  <Button variant="outline" size="sm" onClick={handleExcelDownload} className="h-7 md:h-8 px-2 md:px-3 text-xs">
                    <Download className="mr-1 h-3.5 w-3.5" />
                    엑셀
                  </Button>
                )}
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 인쇄 영역 */}
      <div ref={printAreaRef} className="print-area space-y-4 md:space-y-6">
      {/* 일자별 입출금 합계 */}
      <Card>
        <CardContent className="px-3 pt-4 pb-3 md:px-6 md:pt-6 md:pb-6">
          <div className="flex items-center justify-between mb-3 md:mb-4">
            <h3 className="text-base md:text-lg font-semibold">
              일자: {startDateInfo.formatted} {startDateInfo.dayOfWeek}
            </h3>
          </div>
          <div className="rounded-md border overflow-x-auto max-h-[40vh] md:max-h-[50vh] overflow-y-auto">
            <div className="min-w-[420px] md:min-w-[650px]">
            <table className="w-full caption-bottom text-sm">
              <TableHeader className="sticky top-0 z-10 bg-background shadow-[0_1px_0_0_hsl(var(--border))]">
                <TableRow>
                  <TableHead className="font-semibold text-xs md:text-sm">구분</TableHead>
                  <TableHead className="font-semibold text-right whitespace-nowrap text-xs md:text-sm">입금</TableHead>
                  <TableHead className="font-semibold text-right whitespace-nowrap text-xs md:text-sm">출금</TableHead>
                  <TableHead className="font-semibold text-right whitespace-nowrap text-xs md:text-sm">잔액</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading ? (
                  <TableRow>
                    <TableCell colSpan={4} className="text-center py-8">
                      <div className="flex items-center justify-center gap-2">
                        <Loader2 className="h-5 w-5 animate-spin text-gray-400" />
                        <span className="text-gray-500 text-sm">데이터를 불러오는 중...</span>
                      </div>
                    </TableCell>
                  </TableRow>
                ) : filteredDailyAccounts.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={4} className="text-center py-8 text-muted-foreground text-sm">
                      데이터가 없습니다.
                    </TableCell>
                  </TableRow>
                ) : (
                  <>
                    {/* KRW 계좌들 */}
                    {filteredDailyAccounts
                      .filter(item => item.currency === 'KRW')
                      .map((item) => (
                        <TableRow key={item.id} className="hover:bg-muted/50">
                          <TableCell className="max-w-[140px] md:max-w-[180px] truncate text-xs md:text-sm">{item.category}</TableCell>
                          <TableCell className="text-right whitespace-nowrap text-xs md:text-sm">{formatAmount(item.income)}</TableCell>
                          <TableCell className="text-right whitespace-nowrap text-xs md:text-sm">{formatAmount(item.expense)}</TableCell>
                          <TableCell className="text-right whitespace-nowrap text-xs md:text-sm">{formatAmount(item.balance)}</TableCell>
                        </TableRow>
                      ))}
                    {/* KRW 소계 */}
                    {hasUsdAccounts && (
                      <TableRow className="bg-muted/30 font-medium">
                        <TableCell className="text-xs md:text-sm font-semibold">원화(KRW) 소계</TableCell>
                        <TableCell className="text-right whitespace-nowrap text-xs md:text-sm font-semibold">{formatAmount(accountTotals.krw.income)}</TableCell>
                        <TableCell className="text-right whitespace-nowrap text-xs md:text-sm font-semibold">{formatAmount(accountTotals.krw.expense)}</TableCell>
                        <TableCell className="text-right whitespace-nowrap text-xs md:text-sm font-semibold">{formatAmount(accountTotals.krw.balance)}</TableCell>
                      </TableRow>
                    )}
                    {/* USD 계좌들 */}
                    {hasUsdAccounts && filteredDailyAccounts
                      .filter(item => item.currency === 'USD')
                      .map((item) => (
                        <TableRow key={item.id} className="hover:bg-muted/50">
                          <TableCell className="max-w-[140px] md:max-w-[180px] truncate text-xs md:text-sm">{item.category}</TableCell>
                          <TableCell className="text-right whitespace-nowrap text-xs md:text-sm">{formatUsd(item.income)}</TableCell>
                          <TableCell className="text-right whitespace-nowrap text-xs md:text-sm">{formatUsd(item.expense)}</TableCell>
                          <TableCell className="text-right whitespace-nowrap text-xs md:text-sm">{formatUsd(item.balance)}</TableCell>
                        </TableRow>
                      ))}
                    {/* USD 소계 */}
                    {hasUsdAccounts && (
                      <TableRow className="bg-muted/30 font-medium">
                        <TableCell className="text-xs md:text-sm font-semibold">외국환(USD) 소계</TableCell>
                        <TableCell className="text-right whitespace-nowrap text-xs md:text-sm font-semibold">{formatUsd(accountTotals.usd.income)}</TableCell>
                        <TableCell className="text-right whitespace-nowrap text-xs md:text-sm font-semibold">{formatUsd(accountTotals.usd.expense)}</TableCell>
                        <TableCell className="text-right whitespace-nowrap text-xs md:text-sm font-semibold">{formatUsd(accountTotals.usd.balance)}</TableCell>
                      </TableRow>
                    )}
                  </>
                )}
              </TableBody>
              {filteredDailyAccounts.length > 0 && (
                <TableFooter>
                  {/* 합계 */}
                  <TableRow className="bg-muted/50 font-medium">
                    <TableCell className="font-bold whitespace-nowrap text-xs md:text-sm">합계</TableCell>
                    <TableCell className="text-right font-bold whitespace-nowrap text-xs md:text-sm">{formatAmount(cashAssetTotal.income)}</TableCell>
                    <TableCell className="text-right font-bold whitespace-nowrap text-xs md:text-sm">{formatAmount(cashAssetTotal.expense)}</TableCell>
                    <TableCell className="text-right font-bold whitespace-nowrap text-xs md:text-sm">{formatAmount(cashAssetTotal.balance)}</TableCell>
                  </TableRow>
                </TableFooter>
              )}
            </table>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 예금 입출금 내역 */}
      <Card>
        <CardContent className="px-3 pt-4 pb-3 md:px-6 md:pt-6 md:pb-6">
          <div className="flex items-center justify-center mb-3 md:mb-4 py-1.5 md:py-2 bg-gray-100 rounded-md">
            <h3 className="text-base md:text-lg font-semibold">예금 입출금 내역</h3>
          </div>
          {/* KRW 입출금 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3 md:gap-4">
            {/* KRW 입금 */}
            <div>
              <div className="text-center py-1 md:py-1.5 bg-blue-50 rounded-t-md border border-b-0">
                <span className="font-semibold text-blue-700 text-sm md:text-base">입금 (KRW)</span>
              </div>
              <div className="rounded-b-md border overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="font-semibold text-xs md:text-sm">입금처/적요</TableHead>
                      <TableHead className="font-semibold text-right text-xs md:text-sm">금액</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {isLoading ? (
                      <TableRow>
                        <TableCell colSpan={2} className="text-center py-4 md:py-6">
                          <Loader2 className="h-4 w-4 animate-spin text-gray-400 mx-auto" />
                        </TableCell>
                      </TableRow>
                    ) : filteredDailyAccounts.filter(item => item.currency === 'KRW' && item.income > 0).length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={2} className="text-center py-4 md:py-6 text-muted-foreground text-xs md:text-sm">
                          입금 내역이 없습니다.
                        </TableCell>
                      </TableRow>
                    ) : (
                      filteredDailyAccounts
                        .filter(item => item.currency === 'KRW' && item.income > 0)
                        .map((item) => (
                          <TableRow key={`deposit-${item.id}`} className="hover:bg-muted/50">
                            <TableCell>
                              <div className="text-xs md:text-sm">{item.category}</div>
                            </TableCell>
                            <TableCell className="text-right whitespace-nowrap text-xs md:text-sm">{formatAmount(item.income)}</TableCell>
                          </TableRow>
                        ))
                    )}
                  </TableBody>
                  <TableFooter>
                    <TableRow className="bg-blue-50/50">
                      <TableCell className="font-bold text-xs md:text-sm">입금 합계</TableCell>
                      <TableCell className="text-right font-bold whitespace-nowrap text-xs md:text-sm">{formatAmount(cashAssetTotal.income)}</TableCell>
                    </TableRow>
                  </TableFooter>
                </Table>
              </div>
            </div>

            {/* KRW 출금 */}
            <div>
              <div className="text-center py-1 md:py-1.5 bg-red-50 rounded-t-md border border-b-0">
                <span className="font-semibold text-red-700 text-sm md:text-base">출금 (KRW)</span>
              </div>
              <div className="rounded-b-md border overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="font-semibold text-xs md:text-sm">출금처/적요</TableHead>
                      <TableHead className="font-semibold text-right text-xs md:text-sm">금액</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {isLoading ? (
                      <TableRow>
                        <TableCell colSpan={2} className="text-center py-4 md:py-6">
                          <Loader2 className="h-4 w-4 animate-spin text-gray-400 mx-auto" />
                        </TableCell>
                      </TableRow>
                    ) : filteredDailyAccounts.filter(item => item.currency === 'KRW' && item.expense > 0).length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={2} className="text-center py-4 md:py-6 text-muted-foreground text-xs md:text-sm">
                          출금 내역이 없습니다.
                        </TableCell>
                      </TableRow>
                    ) : (
                      filteredDailyAccounts
                        .filter(item => item.currency === 'KRW' && item.expense > 0)
                        .map((item) => (
                          <TableRow key={`withdrawal-${item.id}`} className="hover:bg-muted/50">
                            <TableCell>
                              <div className="text-xs md:text-sm">{item.category}</div>
                            </TableCell>
                            <TableCell className="text-right whitespace-nowrap text-xs md:text-sm">{formatAmount(item.expense)}</TableCell>
                          </TableRow>
                        ))
                    )}
                  </TableBody>
                  <TableFooter>
                    <TableRow className="bg-red-50/50">
                      <TableCell className="font-bold text-xs md:text-sm">출금 합계</TableCell>
                      <TableCell className="text-right font-bold whitespace-nowrap text-xs md:text-sm">{formatAmount(cashAssetTotal.expense)}</TableCell>
                    </TableRow>
                  </TableFooter>
                </Table>
              </div>
            </div>
          </div>

          {/* USD 입출금 — USD 데이터가 있을 때만 표시 */}
          {hasUsdAccounts && (
            <>
              <div className="flex items-center justify-center mt-4 mb-3 py-1.5 md:py-2 bg-emerald-50 rounded-md">
                <h3 className="text-base md:text-lg font-semibold text-emerald-800">외국환(USD) 입출금 내역</h3>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3 md:gap-4">
                {/* USD 입금 */}
                <div>
                  <div className="text-center py-1 md:py-1.5 bg-emerald-50 rounded-t-md border border-b-0">
                    <span className="font-semibold text-emerald-700 text-sm md:text-base">입금 (USD)</span>
                  </div>
                  <div className="rounded-b-md border overflow-x-auto">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead className="font-semibold text-xs md:text-sm">입금처/적요</TableHead>
                          <TableHead className="font-semibold text-right text-xs md:text-sm">금액</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {filteredDailyAccounts.filter(item => item.currency === 'USD' && item.income > 0).length === 0 ? (
                          <TableRow>
                            <TableCell colSpan={2} className="text-center py-4 md:py-6 text-muted-foreground text-xs md:text-sm">
                              USD 입금 내역이 없습니다.
                            </TableCell>
                          </TableRow>
                        ) : (
                          filteredDailyAccounts
                            .filter(item => item.currency === 'USD' && item.income > 0)
                            .map((item) => (
                              <TableRow key={`usd-deposit-${item.id}`} className="hover:bg-muted/50">
                                <TableCell>
                                  <div className="text-xs md:text-sm">{item.category}</div>
                                </TableCell>
                                <TableCell className="text-right whitespace-nowrap text-xs md:text-sm">{formatUsd(item.income)}</TableCell>
                              </TableRow>
                            ))
                        )}
                      </TableBody>
                      <TableFooter>
                        <TableRow className="bg-emerald-50/50">
                          <TableCell className="font-bold text-xs md:text-sm">입금 합계</TableCell>
                          <TableCell className="text-right font-bold whitespace-nowrap text-xs md:text-sm">{formatUsd(accountTotals.usd.income)}</TableCell>
                        </TableRow>
                      </TableFooter>
                    </Table>
                  </div>
                </div>

                {/* USD 출금 */}
                <div>
                  <div className="text-center py-1 md:py-1.5 bg-orange-50 rounded-t-md border border-b-0">
                    <span className="font-semibold text-orange-700 text-sm md:text-base">출금 (USD)</span>
                  </div>
                  <div className="rounded-b-md border overflow-x-auto">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead className="font-semibold text-xs md:text-sm">출금처/적요</TableHead>
                          <TableHead className="font-semibold text-right text-xs md:text-sm">금액</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {filteredDailyAccounts.filter(item => item.currency === 'USD' && item.expense > 0).length === 0 ? (
                          <TableRow>
                            <TableCell colSpan={2} className="text-center py-4 md:py-6 text-muted-foreground text-xs md:text-sm">
                              USD 출금 내역이 없습니다.
                            </TableCell>
                          </TableRow>
                        ) : (
                          filteredDailyAccounts
                            .filter(item => item.currency === 'USD' && item.expense > 0)
                            .map((item) => (
                              <TableRow key={`usd-withdrawal-${item.id}`} className="hover:bg-muted/50">
                                <TableCell>
                                  <div className="text-xs md:text-sm">{item.category}</div>
                                </TableCell>
                                <TableCell className="text-right whitespace-nowrap text-xs md:text-sm">{formatUsd(item.expense)}</TableCell>
                              </TableRow>
                            ))
                        )}
                      </TableBody>
                      <TableFooter>
                        <TableRow className="bg-orange-50/50">
                          <TableCell className="font-bold text-xs md:text-sm">출금 합계</TableCell>
                          <TableCell className="text-right font-bold whitespace-nowrap text-xs md:text-sm">{formatUsd(accountTotals.usd.expense)}</TableCell>
                        </TableRow>
                      </TableFooter>
                    </Table>
                  </div>
                </div>
              </div>
            </>
          )}
        </CardContent>
      </Card>

      {/* 어음 및 외상매출채권현황 */}
      <Card>
        <CardContent className="px-3 pt-4 pb-3 md:px-6 md:pt-6 md:pb-6">
          <div className="flex items-center justify-between mb-3 md:mb-4">
            <h3 className="text-base md:text-lg font-semibold">어음 및 외상매출채권현황</h3>
          </div>
          <div className="rounded-md border overflow-x-auto max-h-[25vh] md:max-h-[30vh] overflow-y-auto">
            <div className="min-w-[480px] md:min-w-[550px]">
            <table className="w-full caption-bottom text-sm">
              <TableHeader className="sticky top-0 z-10 bg-background shadow-[0_1px_0_0_hsl(var(--border))]">
                <TableRow>
                  <TableHead className="font-semibold text-xs md:text-sm">내용</TableHead>
                  <TableHead className="font-semibold text-right whitespace-nowrap text-xs md:text-sm">현재 잔액</TableHead>
                  <TableHead className="font-semibold text-center whitespace-nowrap text-xs md:text-sm">발행일</TableHead>
                  <TableHead className="font-semibold text-center whitespace-nowrap text-xs md:text-sm">만기일</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading ? (
                  <TableRow>
                    <TableCell colSpan={4} className="text-center py-8">
                      <div className="flex items-center justify-center gap-2">
                        <Loader2 className="h-5 w-5 animate-spin text-gray-400" />
                        <span className="text-gray-500 text-sm">데이터를 불러오는 중...</span>
                      </div>
                    </TableCell>
                  </TableRow>
                ) : filteredNoteReceivables.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={4} className="text-center py-8 text-muted-foreground text-sm">
                      데이터가 없습니다.
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredNoteReceivables.map((item) => (
                    <TableRow key={item.id} className="hover:bg-muted/50">
                      <TableCell className="max-w-[160px] md:max-w-[200px] truncate text-xs md:text-sm">{item.content}</TableCell>
                      <TableCell className="text-right whitespace-nowrap text-xs md:text-sm">{formatAmount(item.currentBalance)}</TableCell>
                      <TableCell className="text-center whitespace-nowrap text-xs md:text-sm">{item.issueDate}</TableCell>
                      <TableCell className="text-center whitespace-nowrap text-xs md:text-sm">{item.dueDate}</TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
              {filteredNoteReceivables.length > 0 && (
                <TableFooter className="sticky bottom-0 z-10 bg-background">
                  <TableRow className="bg-muted/50 font-medium">
                    <TableCell className="font-bold text-xs md:text-sm">합계</TableCell>
                    <TableCell className="text-right font-bold whitespace-nowrap text-xs md:text-sm">{formatAmount(noteReceivableTotal)}</TableCell>
                    <TableCell></TableCell>
                    <TableCell></TableCell>
                  </TableRow>
                </TableFooter>
              )}
            </table>
            </div>
          </div>
        </CardContent>
      </Card>
      </div>
    </PageLayout>
  );
}
