'use client';

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { format } from 'date-fns';
import { Download, FileText, Pencil, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { TableRow, TableCell } from '@/components/ui/table';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
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 { VendorLedgerItem, VendorLedgerSummary } from './types';

// ===== Mock 데이터 생성 =====
const generateMockData = (): VendorLedgerItem[] => {
  return [
    { id: '1', vendorName: '회사명', carryoverBalance: -100000, sales: 0, collection: 0, balance: -100000, paymentDate: '25일' },
    { id: '2', vendorName: '회사명', carryoverBalance: 10000000, sales: 10000000, collection: 10000000, balance: 10000000, paymentDate: '말일' },
    { id: '3', vendorName: '회사명', carryoverBalance: 10000000, sales: 0, collection: 0, balance: 10000000, paymentDate: '15일' },
    { id: '4', vendorName: '회사명', carryoverBalance: 10000000, sales: 0, collection: 0, balance: 10000000, paymentDate: '25일' },
    { id: '5', vendorName: '회사명', carryoverBalance: -100000, sales: 0, collection: 0, balance: -100000, paymentDate: '말일' },
    { id: '6', vendorName: '회사명', carryoverBalance: 10000000, sales: 0, collection: 0, balance: 10000000, paymentDate: '15일' },
    { id: '7', vendorName: '회사명', carryoverBalance: -100000, sales: 0, collection: 0, balance: -100000, paymentDate: '25일' },
  ];
};

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

  // ===== 상태 관리 =====
  const [searchQuery, setSearchQuery] = useState('');
  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'));
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  // 삭제 다이얼로그
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);

  // Mock 데이터
  const [data, setData] = useState<VendorLedgerItem[]>(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 filteredData = useMemo(() => {
    if (!searchQuery) return data;
    return data.filter(item =>
      item.vendorName.includes(searchQuery)
    );
  }, [data, searchQuery]);

  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 === paginatedData.length && paginatedData.length > 0) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(paginatedData.map(item => item.id)));
    }
  }, [selectedItems.size, paginatedData]);

  // ===== 요약 통계 계산 =====
  const summary: VendorLedgerSummary = useMemo(() => {
    return {
      carryoverBalance: 3123000,
      totalSales: 3123000,
      totalCollection: 3123000,
      balance: 3123000,
    };
  }, []);

  // ===== 합계 계산 =====
  const totals = useMemo(() => {
    return filteredData.reduce(
      (acc, item) => ({
        carryoverBalance: acc.carryoverBalance + item.carryoverBalance,
        sales: acc.sales + item.sales,
        collection: acc.collection + item.collection,
        balance: acc.balance + item.balance,
      }),
      { carryoverBalance: 0, sales: 0, collection: 0, balance: 0 }
    );
  }, [filteredData]);

  // ===== 액션 핸들러 =====
  const handleRowClick = useCallback((item: VendorLedgerItem) => {
    router.push(`/ko/accounting/vendor-ledger/${item.id}`);
  }, [router]);

  const handleDeleteClick = useCallback((id: string) => {
    setDeleteTargetId(id);
    setShowDeleteDialog(true);
  }, []);

  const handleConfirmDelete = useCallback(() => {
    if (deleteTargetId) {
      console.log('삭제:', deleteTargetId);
      setData(prev => prev.filter(item => item.id !== deleteTargetId));
      setSelectedItems(prev => {
        const newSet = new Set(prev);
        newSet.delete(deleteTargetId);
        return newSet;
      });
    }
    setShowDeleteDialog(false);
    setDeleteTargetId(null);
  }, [deleteTargetId]);

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

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

  // ===== 통계 카드 =====
  const statCards: StatCard[] = useMemo(() => [
    { label: '전기 이월', value: `${summary.carryoverBalance.toLocaleString()}원`, icon: FileText, iconColor: 'text-blue-500' },
    { label: '매출', value: `${summary.totalSales.toLocaleString()}원`, icon: FileText, iconColor: 'text-green-500' },
    { label: '수금', value: `${summary.totalCollection.toLocaleString()}원`, icon: FileText, iconColor: 'text-orange-500' },
    { label: '잔액', value: `${summary.balance.toLocaleString()}원`, icon: FileText, iconColor: 'text-red-500' },
  ], [summary]);

  // ===== 테이블 컬럼 =====
  const tableColumns: TableColumn[] = useMemo(() => [
    { key: 'no', label: 'No.', className: 'text-center w-[60px]' },
    { key: 'vendorName', label: '거래처명' },
    { key: 'carryoverBalance', label: '이월잔액', className: 'text-right w-[120px]' },
    { key: 'sales', label: '매출', className: 'text-right w-[120px]' },
    { key: 'collection', label: '수금', className: 'text-right w-[120px]' },
    { key: 'balance', label: '잔액', className: 'text-right w-[120px]' },
    { key: 'paymentDate', label: '결제일', className: 'text-center w-[100px]' },
    { key: 'actions', label: '작업', className: 'text-center w-[80px]' },
  ], []);

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

    return (
      <TableRow
        key={item.id}
        className="hover:bg-muted/50 cursor-pointer"
        onClick={() => handleRowClick(item)}
      >
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          <Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(item.id)} />
        </TableCell>
        {/* No. */}
        <TableCell className="text-center text-sm text-gray-500">
          {globalIndex}
        </TableCell>
        {/* 거래처명 */}
        <TableCell className="font-medium">{item.vendorName}</TableCell>
        {/* 이월잔액 */}
        <TableCell className="text-right">
          {item.carryoverBalance !== 0 && (
            <span className={item.carryoverBalance < 0 ? 'text-red-600' : ''}>
              {formatAmount(item.carryoverBalance)}
            </span>
          )}
        </TableCell>
        {/* 매출 */}
        <TableCell className="text-right">{formatAmount(item.sales)}</TableCell>
        {/* 수금 */}
        <TableCell className="text-right">{formatAmount(item.collection)}</TableCell>
        {/* 잔액 */}
        <TableCell className="text-right">{formatAmount(item.balance)}</TableCell>
        {/* 결제일 */}
        <TableCell className="text-center">{item.paymentDate}</TableCell>
        {/* 작업 */}
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          {isSelected && (
            <div className="flex items-center justify-center gap-1">
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8 text-gray-600 hover:text-gray-700 hover:bg-gray-50"
                onClick={() => router.push(`/ko/accounting/vendor-ledger/${item.id}`)}
              >
                <Pencil className="h-4 w-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8 text-red-500 hover:text-red-600 hover:bg-red-50"
                onClick={() => handleDeleteClick(item.id)}
              >
                <Trash2 className="h-4 w-4" />
              </Button>
            </div>
          )}
        </TableCell>
      </TableRow>
    );
  }, [selectedItems, toggleSelection, handleRowClick, handleDeleteClick, router]);

  // ===== 모바일 카드 렌더링 =====
  const renderMobileCard = useCallback((
    item: VendorLedgerItem,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => {
    return (
      <ListMobileCard
        id={item.id}
        title={item.vendorName}
        isSelected={isSelected}
        onToggleSelection={onToggle}
        infoGrid={
          <div className="grid grid-cols-2 gap-3">
            <InfoField label="이월잔액" value={formatAmount(item.carryoverBalance) || '-'} />
            <InfoField label="매출" value={formatAmount(item.sales) || '-'} />
            <InfoField label="수금" value={formatAmount(item.collection) || '-'} />
            <InfoField label="잔액" value={formatAmount(item.balance) || '-'} />
            <InfoField label="결제일" value={item.paymentDate || '-'} />
          </div>
        }
        actions={
          isSelected ? (
            <div className="flex gap-2 w-full">
              <Button variant="outline" className="flex-1" onClick={() => handleRowClick(item)}>
                <Pencil className="w-4 h-4 mr-2" /> 상세
              </Button>
              <Button
                variant="outline"
                className="flex-1 text-red-500 border-red-200 hover:bg-red-50 hover:text-red-600"
                onClick={() => handleDeleteClick(item.id)}
              >
                <Trash2 className="w-4 h-4 mr-2" /> 삭제
              </Button>
            </div>
          ) : undefined
        }
        onCardClick={() => handleRowClick(item)}
      />
    );
  }, [handleRowClick, handleDeleteClick]);

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

  // ===== 테이블 하단 합계 행 =====
  const tableFooter = (
    <TableRow className="bg-gray-100 font-medium">
      <TableCell className="text-center"></TableCell>
      <TableCell className="text-center font-bold">합계</TableCell>
      <TableCell></TableCell>
      <TableCell className="text-right">{formatAmount(totals.carryoverBalance)}</TableCell>
      <TableCell className="text-right">{formatAmount(totals.sales)}</TableCell>
      <TableCell className="text-right">{formatAmount(totals.collection)}</TableCell>
      <TableCell className="text-right">{formatAmount(totals.balance)}</TableCell>
      <TableCell></TableCell>
      <TableCell></TableCell>
    </TableRow>
  );

  return (
    <>
      <IntegratedListTemplateV2
        title="거래처원장"
        description="거래처별 기간 내역을 조회합니다."
        icon={FileText}
        headerActions={headerActions}
        stats={statCards}
        searchValue={searchQuery}
        onSearchChange={setSearchQuery}
        searchPlaceholder="거래처명 검색..."
        tableColumns={tableColumns}
        tableFooter={tableFooter}
        data={paginatedData}
        totalCount={filteredData.length}
        allData={filteredData}
        selectedItems={selectedItems}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        getItemId={(item: VendorLedgerItem) => item.id}
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        pagination={{
          currentPage,
          totalPages,
          totalItems: filteredData.length,
          itemsPerPage,
          onPageChange: setCurrentPage,
        }}
      />

      {/* 삭제 확인 다이얼로그 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>거래처원장 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              이 항목을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmDelete}
              className="bg-red-600 hover:bg-red-700"
            >
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}