'use client';

/**
 * 계좌관리 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 클라이언트 사이드 필터링 (전체 데이터 로드 후 필터)
 * - 삭제/일괄삭제 다이얼로그
 */

import { useState, useMemo, useCallback, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
  Landmark,
  Pencil,
  Trash2,
  Plus,
} from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import { TableRow, TableCell } from '@/components/ui/table';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type ListParams,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import type { Account } from './types';
import {
  BANK_LABELS,
  ACCOUNT_STATUS_LABELS,
  ACCOUNT_STATUS_COLORS,
} from './types';
import { getBankAccounts, deleteBankAccount, deleteBankAccounts } from './actions';

// ===== 계좌번호 마스킹 함수 =====
const maskAccountNumber = (accountNumber: string): string => {
  if (accountNumber.length <= 8) return accountNumber;
  const parts = accountNumber.split('-');
  if (parts.length >= 3) {
    // 1234-****-****-1234 형태
    return parts.map((part, idx) => {
      if (idx === 0 || idx === parts.length - 1) return part;
      return '****';
    }).join('-');
  }
  // 단순 형태: 앞 4자리-****-뒤 4자리
  const first = accountNumber.slice(0, 4);
  const last = accountNumber.slice(-4);
  return `${first}-****-****-${last}`;
};

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

  // ===== 상태 관리 =====
  const itemsPerPage = 20;

  // 로딩 상태
  const [isDeleting, setIsDeleting] = useState(false);

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

  // ===== 액션 핸들러 =====
  const handleRowClick = useCallback((item: Account) => {
    router.push(`/ko/settings/accounts/${item.id}`);
  }, [router]);

  const handleEdit = useCallback((item: Account) => {
    router.push(`/ko/settings/accounts/${item.id}?mode=edit`);
  }, [router]);

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

  const handleConfirmDelete = useCallback(async () => {
    if (!deleteTargetId) return;

    setIsDeleting(true);
    try {
      const result = await deleteBankAccount(Number(deleteTargetId));
      if (result.success) {
        toast.success('계좌가 삭제되었습니다.');
        // 페이지 새로고침으로 데이터 갱신
        window.location.reload();
      } else {
        toast.error(result.error || '계좌 삭제에 실패했습니다.');
      }
    } catch {
      toast.error('서버 오류가 발생했습니다.');
    } finally {
      setIsDeleting(false);
      setShowDeleteDialog(false);
      setDeleteTargetId(null);
    }
  }, [deleteTargetId]);

  const handleBulkDelete = useCallback((selectedIds: string[]) => {
    if (selectedIds.length > 0) {
      setBulkDeleteIds(selectedIds);
      setShowBulkDeleteDialog(true);
    }
  }, []);

  const handleConfirmBulkDelete = useCallback(async () => {
    const ids = bulkDeleteIds.map(id => Number(id));
    setIsDeleting(true);
    try {
      const result = await deleteBankAccounts(ids);
      if (result.success) {
        toast.success(`${result.deletedCount}개의 계좌가 삭제되었습니다.`);
        if (result.error) {
          toast.warning(result.error);
        }
        // 페이지 새로고침으로 데이터 갱신
        window.location.reload();
      } else {
        toast.error(result.error || '계좌 삭제에 실패했습니다.');
      }
    } catch {
      toast.error('서버 오류가 발생했습니다.');
    } finally {
      setIsDeleting(false);
      setShowBulkDeleteDialog(false);
      setBulkDeleteIds([]);
    }
  }, [bulkDeleteIds]);

  const handleCreate = useCallback(() => {
    router.push('/ko/settings/accounts/new');
  }, [router]);

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<Account> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '계좌관리',
      description: '계좌 목록을 관리합니다',
      icon: Landmark,
      basePath: '/settings/accounts',

      // ID 추출
      idField: 'id',
      getItemId: (item: Account) => String(item.id),

      // API 액션
      actions: {
        getList: async (params?: ListParams) => {
          try {
            const result = await getBankAccounts();
            if (result.success && result.data) {
              // 클라이언트 사이드 검색 필터링
              let filteredData = result.data;
              if (params?.search) {
                const search = params.search.toLowerCase();
                filteredData = result.data.filter(item =>
                  item.accountName.toLowerCase().includes(search) ||
                  item.accountNumber.includes(search) ||
                  item.accountHolder.toLowerCase().includes(search) ||
                  BANK_LABELS[item.bankCode]?.toLowerCase().includes(search)
                );
              }

              return {
                success: true,
                data: filteredData,
                totalCount: filteredData.length,
                totalPages: Math.ceil(filteredData.length / itemsPerPage),
              };
            }
            return { success: false, error: result.error || '계좌 목록을 불러오는데 실패했습니다.' };
          } catch {
            return { success: false, error: '서버 오류가 발생했습니다.' };
          }
        },
      },

      // 테이블 컬럼
      columns: [
        { key: 'no', label: '번호', className: 'text-center w-[60px]' },
        { key: 'bank', label: '은행', className: 'min-w-[100px]' },
        { key: 'accountNumber', label: '계좌번호', className: 'min-w-[160px]' },
        { key: 'accountName', label: '계좌명', className: 'min-w-[120px]' },
        { key: 'accountHolder', label: '예금주', className: 'min-w-[80px]' },
        { key: 'status', label: '상태', className: 'min-w-[80px]' },
        { key: 'actions', label: '작업', className: 'w-[100px] text-right' },
      ],

      // 클라이언트 사이드 필터링
      clientSideFiltering: true,
      itemsPerPage,

      // 검색
      searchPlaceholder: '은행명, 계좌번호, 계좌명, 예금주 검색...',

      // 헤더 액션
      headerActions: () => (
        <Button className="ml-auto" onClick={handleCreate}>
          <Plus className="w-4 h-4 mr-2" />
          계좌 등록
        </Button>
      ),

      // 일괄 삭제 핸들러
      onBulkDelete: handleBulkDelete,

      // 테이블 행 렌더링
      renderTableRow: (
        item: Account,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Account>
      ) => {
        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={handlers.isSelected} onCheckedChange={handlers.onToggle} />
            </TableCell>
            <TableCell className="text-muted-foreground text-center">{globalIndex}</TableCell>
            <TableCell>{BANK_LABELS[item.bankCode] || item.bankCode}</TableCell>
            <TableCell className="font-mono">{maskAccountNumber(item.accountNumber)}</TableCell>
            <TableCell>{item.accountName}</TableCell>
            <TableCell>{item.accountHolder}</TableCell>
            <TableCell>
              <Badge className={ACCOUNT_STATUS_COLORS[item.status]}>
                {ACCOUNT_STATUS_LABELS[item.status]}
              </Badge>
            </TableCell>
            <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
              {handlers.isSelected && (
                <div className="flex items-center justify-end gap-1">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => handleEdit(item)}
                    title="수정"
                  >
                    <Pencil className="w-4 h-4" />
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => handleDeleteClick(String(item.id))}
                    title="삭제"
                  >
                    <Trash2 className="w-4 h-4 text-red-500" />
                  </Button>
                </div>
              )}
            </TableCell>
          </TableRow>
        );
      },

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: Account,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Account>
      ) => {
        return (
          <ListMobileCard
            key={item.id}
            id={String(item.id)}
            title={item.accountName}
            headerBadges={
              <div className="flex items-center gap-2 flex-wrap">
                <Badge variant="outline" className="text-xs">
                  #{globalIndex}
                </Badge>
                <span className="text-xs text-muted-foreground">
                  {BANK_LABELS[item.bankCode] || item.bankCode}
                </span>
              </div>
            }
            statusBadge={
              <Badge className={ACCOUNT_STATUS_COLORS[item.status]}>
                {ACCOUNT_STATUS_LABELS[item.status]}
              </Badge>
            }
            isSelected={handlers.isSelected}
            onToggleSelection={handlers.onToggle}
            onClick={() => handleRowClick(item)}
            infoGrid={
              <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                <InfoField label="계좌번호" value={maskAccountNumber(item.accountNumber)} />
                <InfoField label="예금주" value={item.accountHolder} />
              </div>
            }
            actions={
              handlers.isSelected ? (
                <div className="flex gap-2 flex-wrap">
                  <Button
                    variant="default"
                    size="default"
                    className="flex-1 min-w-[100px] h-11"
                    onClick={(e) => { e.stopPropagation(); handleEdit(item); }}
                  >
                    <Pencil className="h-4 w-4 mr-2" />
                    수정
                  </Button>
                  <Button
                    variant="outline"
                    size="default"
                    className="flex-1 min-w-[100px] h-11 border-red-200 text-red-600 hover:border-red-300 bg-transparent"
                    onClick={(e) => { e.stopPropagation(); handleDeleteClick(String(item.id)); }}
                  >
                    <Trash2 className="h-4 w-4 mr-2" />
                    삭제
                  </Button>
                </div>
              ) : undefined
            }
          />
        );
      },
    }),
    [handleCreate, handleRowClick, handleEdit, handleDeleteClick, handleBulkDelete]
  );

  return (
    <>
      <UniversalListPage config={config} />

      {/* 단일 삭제 확인 다이얼로그 */}
      <DeleteConfirmDialog
        open={showDeleteDialog}
        onOpenChange={setShowDeleteDialog}
        onConfirm={handleConfirmDelete}
        title="계좌 삭제"
        description={
          <>
            계좌를 정말 삭제하시겠습니까?
            <br />
            <span className="text-muted-foreground text-sm">
              삭제된 계좌의 과거 사용 내역은 보존됩니다.
            </span>
          </>
        }
        loading={isDeleting}
      />

      {/* 다중 삭제 확인 다이얼로그 */}
      <DeleteConfirmDialog
        open={showBulkDeleteDialog}
        onOpenChange={setShowBulkDeleteDialog}
        onConfirm={handleConfirmBulkDelete}
        title="계좌 삭제"
        description={
          <>
            선택하신 <strong>{bulkDeleteIds.length}개</strong>의 계좌를 정말 삭제하시겠습니까?
            <br />
            <span className="text-muted-foreground text-sm">
              삭제된 계좌의 과거 사용 내역은 보존됩니다.
            </span>
          </>
        }
        loading={isDeleting}
      />
    </>
  );
}