'use client';

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { format } from 'date-fns';
import {
  Banknote,
  Pencil,
  Save,
  Trash2,
  RefreshCw,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
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 {
  DepositRecord,
  DepositStatus,
  DepositType,
  SortOption,
} from './types';
import {
  SORT_OPTIONS,
  DEPOSIT_STATUS_LABELS,
  DEPOSIT_STATUS_COLORS,
  DEPOSIT_TYPE_LABELS,
  DEPOSIT_TYPE_FILTER_OPTIONS,
  ACCOUNT_SUBJECT_OPTIONS,
} from './types';

// ===== Mock 데이터 생성 =====
const generateMockData = (): DepositRecord[] => {
  const depositTypes: DepositType[] = ['unset', 'salesRevenue', 'advance', 'suspense', 'rentalIncome', 'interestIncome', 'depositRefund', 'borrowings', 'capital', 'vatRefund', 'other'];
  const statuses: DepositStatus[] = ['inputWaiting', 'requesting', 'rejected', 'pending', 'incomplete', 'error', 'confirmed'];
  const vendors = ['(주)삼성전자', '현대자동차', 'LG전자', 'SK하이닉스', '네이버', '카카오', '쿠팡', '배달의민족'];
  const accountNames = ['국민은행 1234', '신한은행 5678', '우리은행 9012', '하나은행 3456'];
  const depositorNames = ['홍길동', '김철수', '이영희', '박민수', '최지영'];

  const amounts = [1000000, 2500000, 500000, 3000000, 1500000, 800000, 4000000, 10000000];

  return Array.from({ length: 50 }, (_, i) => {
    const depositAmount = amounts[i % amounts.length] + (i * 100000);

    return {
      id: `deposit-${i + 1}`,
      depositDate: format(new Date(2025, 8, (i % 17) + 1), 'yyyy-MM-dd'),
      depositAmount,
      accountName: accountNames[i % accountNames.length],
      depositorName: depositorNames[i % depositorNames.length],
      note: i % 3 === 0 ? '입금 내역' : '',
      depositType: depositTypes[i % depositTypes.length],
      vendorId: `vendor-${i % vendors.length}`,
      vendorName: i % 4 === 0 ? '' : vendors[i % vendors.length],
      status: statuses[i % statuses.length],
      createdAt: '2025-12-18T00:00:00.000Z',
      updatedAt: '2025-12-18T00:00:00.000Z',
    };
  });
};

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

  // ===== 상태 관리 =====
  const [searchQuery, setSearchQuery] = useState('');
  const [sortOption, setSortOption] = useState<SortOption>('latest');
  const [depositTypeFilter, setDepositTypeFilter] = useState<string>('all');
  const [vendorFilter, setVendorFilter] = useState<string>('all');
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

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

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

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

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

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

  // Mock 데이터
  const [data, setData] = useState<DepositRecord[]>(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(() => {
    let result = data.filter(item =>
      item.depositorName.includes(searchQuery) ||
      item.accountName.includes(searchQuery) ||
      item.note.includes(searchQuery) ||
      item.vendorName.includes(searchQuery)
    );

    // 거래처 필터
    if (vendorFilter !== 'all') {
      result = result.filter(item => item.vendorName === vendorFilter);
    }

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

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

    return result;
  }, [data, searchQuery, vendorFilter, depositTypeFilter, 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 handleRowClick = useCallback((item: DepositRecord) => {
    router.push(`/ko/accounting/deposits/${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 handleRefresh = useCallback(() => {
    console.log('새로고침: 은행 계좌 입금 내역 최신 데이터 조회');
    // TODO: API 호출로 최신 데이터 조회
  }, []);

  // ===== 통계 카드 (총 입금, 당월 입금, 거래처 미설정, 입금유형 미설정) =====
  const statCards: StatCard[] = useMemo(() => {
    const totalDeposit = data.reduce((sum, d) => sum + d.depositAmount, 0);

    // 당월 입금
    const currentMonth = new Date().getMonth();
    const currentYear = new Date().getFullYear();
    const monthlyDeposit = data
      .filter(d => {
        const date = new Date(d.depositDate);
        return date.getMonth() === currentMonth && date.getFullYear() === currentYear;
      })
      .reduce((sum, d) => sum + d.depositAmount, 0);

    // 거래처 미설정 건수
    const vendorUnsetCount = data.filter(d => !d.vendorName).length;

    // 입금유형 미설정 건수
    const depositTypeUnsetCount = data.filter(d => d.depositType === 'unset').length;

    return [
      { label: '총 입금', value: `${totalDeposit.toLocaleString()}원`, icon: Banknote, iconColor: 'text-blue-500' },
      { label: '당월 입금', value: `${monthlyDeposit.toLocaleString()}원`, icon: Banknote, iconColor: 'text-green-500' },
      { label: '거래처 미설정', value: `${vendorUnsetCount}건`, icon: Banknote, iconColor: 'text-orange-500' },
      { label: '입금유형 미설정', value: `${depositTypeUnsetCount}건`, icon: Banknote, iconColor: 'text-red-500' },
    ];
  }, [data]);

  // ===== 테이블 컬럼 =====
  const tableColumns: TableColumn[] = useMemo(() => [
    { key: 'depositDate', label: '입금일' },
    { key: 'accountName', label: '입금계좌' },
    { key: 'depositorName', label: '입금자명' },
    { key: 'depositAmount', label: '입금금액', className: 'text-right' },
    { key: 'vendorName', label: '거래처' },
    { key: 'note', label: '적요' },
    { key: 'depositType', label: '입금유형', className: 'text-center' },
    { key: 'actions', label: '작업', className: 'text-center w-[80px]' },
  ], []);

  // ===== 테이블 행 렌더링 =====
  const renderTableRow = useCallback((item: DepositRecord, index: number, globalIndex: number) => {
    const isSelected = selectedItems.has(item.id);
    const isVendorUnset = !item.vendorName;
    const isDepositTypeUnset = item.depositType === 'unset';

    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>
        {/* 입금일 */}
        <TableCell>{item.depositDate}</TableCell>
        {/* 입금계좌 */}
        <TableCell>{item.accountName}</TableCell>
        {/* 입금자명 */}
        <TableCell>{item.depositorName}</TableCell>
        {/* 입금금액 */}
        <TableCell className="text-right font-medium">{item.depositAmount.toLocaleString()}</TableCell>
        {/* 거래처 */}
        <TableCell className={isVendorUnset ? 'text-red-500 font-medium' : ''}>
          {item.vendorName || '미설정'}
        </TableCell>
        {/* 적요 */}
        <TableCell className="text-gray-500">{item.note || '-'}</TableCell>
        {/* 입금유형 */}
        <TableCell className="text-center">
          <Badge
            variant="outline"
            className={isDepositTypeUnset ? 'border-red-300 text-red-500 bg-red-50' : ''}
          >
            {DEPOSIT_TYPE_LABELS[item.depositType]}
          </Badge>
        </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/deposits/${item.id}?mode=edit`)}
              >
                <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]);

  // ===== 모바일 카드 렌더링 =====
  const renderMobileCard = useCallback((
    item: DepositRecord,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => {
    return (
      <ListMobileCard
        id={item.id}
        title={item.depositorName}
        headerBadges={
          <>
            <Badge variant="outline">{DEPOSIT_TYPE_LABELS[item.depositType]}</Badge>
            <Badge className={DEPOSIT_STATUS_COLORS[item.status]}>
              {DEPOSIT_STATUS_LABELS[item.status]}
            </Badge>
          </>
        }
        isSelected={isSelected}
        onToggleSelection={onToggle}
        infoGrid={
          <div className="grid grid-cols-2 gap-3">
            <InfoField label="입금일" value={item.depositDate} />
            <InfoField label="입금액" value={`${item.depositAmount.toLocaleString()}원`} />
            <InfoField label="입금계좌" value={item.accountName} />
            <InfoField label="거래처" value={item.vendorName || '-'} />
          </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}
    />
  );

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

  // 계정과목명 저장 확정
  const handleConfirmSaveAccountSubject = useCallback(() => {
    console.log('계정과목명 저장:', selectedAccountSubject, '선택된 항목:', Array.from(selectedItems));
    // TODO: API 호출로 저장
    setShowSaveDialog(false);
    setSelectedItems(new Set());
  }, [selectedAccountSubject, selectedItems]);

  // ===== 거래처 목록 (필터용) =====
  const vendorOptions = useMemo(() => {
    const uniqueVendors = [...new Set(data.map(d => d.vendorName).filter(v => v))];
    return [
      { value: 'all', label: '전체' },
      ...uniqueVendors.map(v => ({ value: v, label: v }))
    ];
  }, [data]);

  // ===== 테이블 헤더 액션 (필터들) =====
  const tableHeaderActions = (
    <div className="flex items-center gap-2 flex-wrap">
      {/* 거래처 필터 */}
      <Select value={vendorFilter} onValueChange={setVendorFilter}>
        <SelectTrigger className="w-[140px]">
          <SelectValue placeholder="거래처" />
        </SelectTrigger>
        <SelectContent>
          {vendorOptions.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      {/* 입금유형 필터 */}
      <Select value={depositTypeFilter} onValueChange={setDepositTypeFilter}>
        <SelectTrigger className="w-[130px]">
          <SelectValue placeholder="입금유형" />
        </SelectTrigger>
        <SelectContent>
          {DEPOSIT_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 accountSubjectSelector = (
    <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}
      >
        <RefreshCw className="h-4 w-4 mr-2" />
        새로고침
      </Button>
    </div>
  );

  // ===== 테이블 합계 계산 =====
  const tableTotals = useMemo(() => {
    const totalAmount = filteredData.reduce((sum, item) => sum + item.depositAmount, 0);
    return { totalAmount };
  }, [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 className="text-right font-bold">{tableTotals.totalAmount.toLocaleString()}</TableCell>
      <TableCell></TableCell>
      <TableCell></TableCell>
      <TableCell></TableCell>
      <TableCell></TableCell>
    </TableRow>
  );

  return (
    <>
      <IntegratedListTemplateV2
        title="입금관리"
        description="입금 내역을 등록합니다"
        icon={Banknote}
        headerActions={headerActions}
        stats={statCards}
        searchValue={searchQuery}
        onSearchChange={setSearchQuery}
        searchPlaceholder="입금자명, 계좌명, 적요, 거래처 검색..."
        beforeTableContent={accountSubjectSelector}
        tableHeaderActions={tableHeaderActions}
        tableColumns={tableColumns}
        tableFooter={tableFooter}
        data={paginatedData}
        totalCount={filteredData.length}
        allData={filteredData}
        selectedItems={selectedItems}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        getItemId={(item: DepositRecord) => item.id}
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        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)}>
              취소
            </Button>
            <Button
              onClick={handleConfirmSaveAccountSubject}
              className="bg-orange-500 hover:bg-orange-600"
            >
              확인
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 삭제 확인 다이얼로그 */}
      <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>

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