'use client';

import { useState, useMemo, useCallback } from 'react';
import { format, parseISO } from 'date-fns';
import { ko } from 'date-fns/locale';
import { Download, FileText } 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 { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
import { Badge } from '@/components/ui/badge';
import type { NoteReceivableItem, DailyAccountItem } from './types';
import { MATCH_STATUS_LABELS, MATCH_STATUS_COLORS } from './types';

// ===== Mock 데이터 =====
const generateMockNoteReceivables = (): NoteReceivableItem[] => {
  return [
    {
      id: '1',
      content: '(수취어음) 거래처명 - 12312123',
      currentBalance: 1000000,
      issueDate: '2025-12-12',
      dueDate: '2025-12-13',
    },
  ];
};

const generateMockDailyAccounts = (): DailyAccountItem[] => {
  return [
    {
      id: '1',
      category: '국민 1231...3121',
      matchStatus: 'matched',
      carryover: 1000000,
      income: 1000000,
      expense: 1000000,
      balance: 1000000,
      currency: 'KRW',
    },
    {
      id: '2',
      category: '농협 1231...1321',
      matchStatus: 'unmatched',
      carryover: 123123,
      income: 0,
      expense: 0,
      balance: 123123,
      currency: 'KRW',
    },
  ];
};

export function DailyReport() {
  // ===== 상태 관리 =====
  const [startDate, setStartDate] = useState(() => format(new Date(2025, 8, 1), 'yyyy-MM-dd'));
  const [endDate, setEndDate] = useState(() => format(new Date(2025, 8, 3), 'yyyy-MM-dd'));

  // Mock 데이터
  const [noteReceivables] = useState<NoteReceivableItem[]>(generateMockNoteReceivables);
  const [dailyAccounts] = useState<DailyAccountItem[]>(generateMockDailyAccounts);

  // ===== 금액 포맷 =====
  const formatAmount = useCallback((amount: number) => {
    if (amount === 0) return '0';
    return amount.toLocaleString();
  }, []);

  // ===== 어음 합계 =====
  const noteReceivableTotal = useMemo(() => {
    return noteReceivables.reduce((sum, item) => sum + item.currentBalance, 0);
  }, [noteReceivables]);

  // ===== 일별 계좌 합계 =====
  const accountTotals = useMemo(() => {
    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 };
  }, [dailyAccounts]);

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

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

  // ===== 엑셀 다운로드 =====
  const handleExcelDownload = useCallback(() => {
    console.log('엑셀 다운로드:', { startDate, endDate });
  }, [startDate, endDate]);

  // ===== 헤더 액션 =====
  const headerActions = (
    <DateRangeSelector
      startDate={startDate}
      endDate={endDate}
      onStartDateChange={setStartDate}
      onEndDateChange={setEndDate}
      extraActions={
        <Button variant="outline" size="sm" onClick={handleExcelDownload}>
          <Download className="mr-2 h-4 w-4" />
          엑셀 다운로드
        </Button>
      }
    />
  );

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

      {/* 헤더 액션 (달력, 버튼 등) - 타이틀 아래 배치 (IntegratedListTemplateV2 스타일) */}
      <div className="flex items-center gap-2 flex-wrap">
        {headerActions}
      </div>

      {/* 어음 및 외상매출채권현황 */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-semibold">어음 및 외상매출채권현황</h3>
          </div>
          <div className="rounded-md border overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="font-semibold">내용</TableHead>
                  <TableHead className="font-semibold text-right w-[150px]">현재 잔액</TableHead>
                  <TableHead className="font-semibold text-center w-[120px]">발행일</TableHead>
                  <TableHead className="font-semibold text-center w-[120px]">만기일</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {noteReceivables.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={4} className="text-center py-8 text-muted-foreground">
                      데이터가 없습니다.
                    </TableCell>
                  </TableRow>
                ) : (
                  noteReceivables.map((item) => (
                    <TableRow key={item.id} className="hover:bg-muted/50">
                      <TableCell>{item.content}</TableCell>
                      <TableCell className="text-right">{formatAmount(item.currentBalance)}</TableCell>
                      <TableCell className="text-center">{item.issueDate}</TableCell>
                      <TableCell className="text-center">{item.dueDate}</TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
              {noteReceivables.length > 0 && (
                <TableFooter>
                  <TableRow className="bg-muted/50 font-medium">
                    <TableCell className="font-bold">합계</TableCell>
                    <TableCell className="text-right font-bold">{formatAmount(noteReceivableTotal)}</TableCell>
                    <TableCell></TableCell>
                    <TableCell></TableCell>
                  </TableRow>
                </TableFooter>
              )}
            </Table>
          </div>
        </CardContent>
      </Card>

      {/* 일자별 상세 */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-semibold">
              일자: {selectedDateInfo.formatted} {selectedDateInfo.dayOfWeek}
            </h3>
          </div>
          <div className="rounded-md border overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="font-semibold w-[200px]">구분</TableHead>
                  <TableHead className="font-semibold text-center w-[80px]">상태</TableHead>
                  <TableHead className="font-semibold text-right w-[150px]">전월 이월</TableHead>
                  <TableHead className="font-semibold text-right w-[120px]">수입</TableHead>
                  <TableHead className="font-semibold text-right w-[120px]">지출</TableHead>
                  <TableHead className="font-semibold text-right w-[120px]">잔액</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {dailyAccounts.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
                      데이터가 없습니다.
                    </TableCell>
                  </TableRow>
                ) : (
                  <>
                    {/* KRW 계좌들 */}
                    {dailyAccounts
                      .filter(item => item.currency === 'KRW')
                      .map((item) => (
                        <TableRow key={item.id} className="hover:bg-muted/50">
                          <TableCell>{item.category}</TableCell>
                          <TableCell className="text-center">
                            <Badge className={MATCH_STATUS_COLORS[item.matchStatus]}>
                              {MATCH_STATUS_LABELS[item.matchStatus]}
                            </Badge>
                          </TableCell>
                          <TableCell className="text-right">{formatAmount(item.carryover)}</TableCell>
                          <TableCell className="text-right">{formatAmount(item.income)}</TableCell>
                          <TableCell className="text-right">{formatAmount(item.expense)}</TableCell>
                          <TableCell className="text-right">{formatAmount(item.balance)}</TableCell>
                        </TableRow>
                      ))}
                  </>
                )}
              </TableBody>
              {dailyAccounts.length > 0 && (
                <TableFooter>
                  {/* 외화원 (USD) 합계 */}
                  <TableRow className="bg-blue-50/50">
                    <TableCell className="font-semibold">외화원 (USD) 합계</TableCell>
                    <TableCell></TableCell>
                    <TableCell className="text-right">${formatAmount(accountTotals.usd.carryover)}</TableCell>
                    <TableCell className="text-right">${formatAmount(accountTotals.usd.income)}</TableCell>
                    <TableCell className="text-right">${formatAmount(accountTotals.usd.expense)}</TableCell>
                    <TableCell className="text-right">${formatAmount(accountTotals.usd.balance)}</TableCell>
                  </TableRow>
                  {/* 현금성 자산 합계 */}
                  <TableRow className="bg-muted/50 font-medium">
                    <TableCell className="font-bold">현금성 자산 합계</TableCell>
                    <TableCell></TableCell>
                    <TableCell className="text-right font-bold">{formatAmount(cashAssetTotal.carryover)}</TableCell>
                    <TableCell className="text-right font-bold">{formatAmount(cashAssetTotal.income)}</TableCell>
                    <TableCell className="text-right font-bold">{formatAmount(cashAssetTotal.expense)}</TableCell>
                    <TableCell className="text-right font-bold">{formatAmount(cashAssetTotal.balance)}</TableCell>
                  </TableRow>
                </TableFooter>
              )}
            </Table>
          </div>
        </CardContent>
      </Card>
    </PageLayout>
  );
}