'use client';

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
  Building2,
  Pencil,
  Trash2,
  Eye,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
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 { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import type {
  Vendor,
  VendorCategory,
  CreditRating,
  TransactionGrade,
  BadDebtStatus,
  SortOption,
} from './types';
import {
  VENDOR_CATEGORY_OPTIONS,
  VENDOR_CATEGORY_LABELS,
  VENDOR_CATEGORY_COLORS,
  CREDIT_RATING_OPTIONS,
  CREDIT_RATING_COLORS,
  TRANSACTION_GRADE_OPTIONS,
  TRANSACTION_GRADE_LABELS,
  TRANSACTION_GRADE_COLORS,
  BAD_DEBT_STATUS_OPTIONS,
  BAD_DEBT_STATUS_LABELS,
  BAD_DEBT_STATUS_COLORS,
  SORT_OPTIONS,
} from './types';

// ===== Mock 데이터 생성 =====
const generateMockData = (): Vendor[] => {
  const categories: VendorCategory[] = ['sales', 'purchase', 'both'];
  const creditRatings: CreditRating[] = ['AAA', 'AA', 'A', 'BBB', 'BB', 'B'];
  const transactionGrades: TransactionGrade[] = ['A', 'B', 'C', 'D', 'E'];
  const badDebtStatuses: BadDebtStatus[] = ['none', 'badDebt', 'normal'];
  const vendorNames = [
    '(주)삼성전자', '현대자동차', 'LG전자', 'SK하이닉스', '네이버',
    '카카오', '쿠팡', '배달의민족', '토스', '야놀자',
  ];

  return Array.from({ length: 30 }, (_, i) => ({
    id: `vendor-${i + 1}`,
    vendorCode: `V${String(i + 1).padStart(4, '0')}`,
    businessNumber: `123-45-${String(67890 + i).padStart(5, '0')}`,
    vendorName: vendorNames[i % vendorNames.length],
    representativeName: `대표자${i + 1}`,
    category: categories[i % categories.length],
    businessType: '제조업',
    businessCategory: '전자제품',
    zipCode: '06234',
    address1: '서울특별시 강남구 테헤란로 123',
    address2: `${i + 1}층`,
    phone: '02-1234-5678',
    mobile: '010-1234-5678',
    fax: '02-1234-5679',
    email: `vendor${i + 1}@example.com`,
    managerName: `담당자${i + 1}`,
    managerPhone: '010-9876-5432',
    systemManager: `관리자${i + 1}`,
    logoUrl: '',
    purchasePaymentDay: ((i % 3) + 1) * 10,
    salesPaymentDay: ((i % 3) + 1) * 5 + 10,
    creditRating: creditRatings[i % creditRatings.length],
    transactionGrade: transactionGrades[i % transactionGrades.length],
    taxInvoiceEmail: `tax${i + 1}@example.com`,
    bankName: 'kb',
    accountNumber: `123456789${i}`,
    accountHolder: vendorNames[i % vendorNames.length],
    outstandingAmount: (i % 5) * 5000000,
    overdueAmount: (i % 3) * 1000000,
    overdueDays: (i % 4) * 10,
    unpaidAmount: (i % 4) * 3000000,
    badDebtStatus: badDebtStatuses[i % badDebtStatuses.length],
    overdueToggle: i % 2 === 0,
    badDebtToggle: i % 3 === 0,
    memos: [],
    createdAt: '2025-12-18T00:00:00.000Z',
    updatedAt: '2025-12-18T00:00:00.000Z',
  }));
};

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

  // ===== 상태 관리 =====
  const [searchQuery, setSearchQuery] = useState('');
  const [sortOption, setSortOption] = useState<SortOption>('latest');
  const [categoryFilter, setCategoryFilter] = useState<string>('all');
  const [creditRatingFilter, setCreditRatingFilter] = useState<string>('all');
  const [transactionGradeFilter, setTransactionGradeFilter] = useState<string>('all');
  const [badDebtFilter, setBadDebtFilter] = useState<string>('all');
  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<Vendor[]>(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.vendorName.includes(searchQuery) ||
      item.vendorCode.includes(searchQuery) ||
      item.businessNumber.includes(searchQuery)
    );

    // 구분 필터
    if (categoryFilter !== 'all') {
      result = result.filter(item => item.category === categoryFilter);
    }

    // 신용등급 필터
    if (creditRatingFilter !== 'all') {
      result = result.filter(item => item.creditRating === creditRatingFilter);
    }

    // 거래등급 필터
    if (transactionGradeFilter !== 'all') {
      result = result.filter(item => item.transactionGrade === transactionGradeFilter);
    }

    // 악성채권 필터
    if (badDebtFilter !== 'all') {
      result = result.filter(item => item.badDebtStatus === badDebtFilter);
    }

    // 정렬
    switch (sortOption) {
      case 'latest':
        result.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
        break;
      case 'oldest':
        result.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
        break;
      case 'nameAsc':
        result.sort((a, b) => a.vendorName.localeCompare(b.vendorName));
        break;
      case 'nameDesc':
        result.sort((a, b) => b.vendorName.localeCompare(a.vendorName));
        break;
      case 'outstandingHigh':
        result.sort((a, b) => b.outstandingAmount - a.outstandingAmount);
        break;
      case 'outstandingLow':
        result.sort((a, b) => a.outstandingAmount - b.outstandingAmount);
        break;
    }

    return result;
  }, [data, searchQuery, categoryFilter, creditRatingFilter, transactionGradeFilter, badDebtFilter, 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: Vendor) => {
    router.push(`/ko/accounting/vendors/${item.id}`);
  }, [router]);

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

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

  const handleConfirmDelete = useCallback(() => {
    if (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 statCards: StatCard[] = useMemo(() => {
    const totalCount = data.length;
    const salesCount = data.filter(d => d.category === 'sales' || d.category === 'both').length;
    const purchaseCount = data.filter(d => d.category === 'purchase' || d.category === 'both').length;

    return [
      { label: '전체 거래처', value: `${totalCount}개`, icon: Building2, iconColor: 'text-blue-500' },
      { label: '매출 거래처', value: `${salesCount}개`, icon: Building2, iconColor: 'text-green-500' },
      { label: '매입 거래처', value: `${purchaseCount}개`, icon: Building2, iconColor: 'text-orange-500' },
    ];
  }, [data]);

  // ===== 테이블 컬럼 =====
  const tableColumns: TableColumn[] = useMemo(() => [
    { key: 'no', label: '번호', className: 'text-center w-[60px]' },
    { key: 'category', label: '구분', className: 'text-center w-[100px]' },
    { key: 'vendorName', label: '거래처명' },
    { key: 'purchasePaymentDay', label: '매입 결제일', className: 'text-center w-[100px]' },
    { key: 'salesPaymentDay', label: '매출 결제일', className: 'text-center w-[100px]' },
    { key: 'creditRating', label: '신용등급', className: 'text-center w-[90px]' },
    { key: 'transactionGrade', label: '거래등급', className: 'text-center w-[100px]' },
    { key: 'outstandingAmount', label: '미수금', className: 'text-right w-[120px]' },
    { key: 'badDebtStatus', label: '악성채권', className: 'text-center w-[90px]' },
    { key: 'actions', label: '작업', className: 'text-center w-[150px]' },
  ], []);

  // ===== 테이블 행 렌더링 =====
  const renderTableRow = useCallback((item: Vendor, 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>
        {/* 번호 */}
        <TableCell className="text-center text-sm text-gray-500">{globalIndex}</TableCell>
        {/* 구분 */}
        <TableCell className="text-center">
          <Badge className={VENDOR_CATEGORY_COLORS[item.category]}>
            {VENDOR_CATEGORY_LABELS[item.category]}
          </Badge>
        </TableCell>
        {/* 거래처명 */}
        <TableCell className="font-medium">{item.vendorName}</TableCell>
        {/* 매입 결제일 */}
        <TableCell className="text-center">{item.purchasePaymentDay}일</TableCell>
        {/* 매출 결제일 */}
        <TableCell className="text-center">{item.salesPaymentDay}일</TableCell>
        {/* 신용등급 */}
        <TableCell className="text-center">
          <Badge className={CREDIT_RATING_COLORS[item.creditRating]}>
            {item.creditRating}
          </Badge>
        </TableCell>
        {/* 거래등급 */}
        <TableCell className="text-center">
          <Badge className={TRANSACTION_GRADE_COLORS[item.transactionGrade]}>
            {TRANSACTION_GRADE_LABELS[item.transactionGrade]}
          </Badge>
        </TableCell>
        {/* 미수금 */}
        <TableCell className="text-right">
          {item.outstandingAmount > 0 ? (
            <span className="text-red-600 font-medium">{item.outstandingAmount.toLocaleString()}원</span>
          ) : (
            <span className="text-gray-500">-</span>
          )}
        </TableCell>
        {/* 악성채권 */}
        <TableCell className="text-center">
          {item.badDebtStatus === 'none' ? (
            <span className="text-gray-400">-</span>
          ) : (
            <Badge className={BAD_DEBT_STATUS_COLORS[item.badDebtStatus]}>
              {BAD_DEBT_STATUS_LABELS[item.badDebtStatus]}
            </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"
                onClick={() => handleEdit(item)}
              >
                <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, handleEdit, handleDeleteClick]);

  // ===== 모바일 카드 렌더링 =====
  const renderMobileCard = useCallback((
    item: Vendor,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => {
    return (
      <ListMobileCard
        id={item.id}
        title={item.vendorName}
        headerBadges={
          <>
            <Badge className={VENDOR_CATEGORY_COLORS[item.category]}>
              {VENDOR_CATEGORY_LABELS[item.category]}
            </Badge>
            <Badge className={CREDIT_RATING_COLORS[item.creditRating]}>
              {item.creditRating}
            </Badge>
          </>
        }
        isSelected={isSelected}
        onToggleSelection={onToggle}
        infoGrid={
          <div className="grid grid-cols-2 gap-3">
            <InfoField label="거래처코드" value={item.vendorCode} />
            <InfoField label="거래등급" value={TRANSACTION_GRADE_LABELS[item.transactionGrade]} />
            <InfoField
              label="미수금"
              value={item.outstandingAmount > 0 ? `${item.outstandingAmount.toLocaleString()}원` : '-'}
              className={item.outstandingAmount > 0 ? 'text-red-600' : ''}
            />
            <InfoField label="결제일" value={`매입 ${item.purchasePaymentDay}일 / 매출 ${item.salesPaymentDay}일`} />
          </div>
        }
        actions={
          isSelected ? (
            <div className="flex gap-2 w-full">
              <Button variant="outline" className="flex-1" onClick={() => handleRowClick(item)}>
                <Eye className="w-4 h-4 mr-2" /> 상세
              </Button>
              <Button variant="outline" className="flex-1" onClick={() => handleEdit(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
        }
        onClick={() => handleRowClick(item)}
      />
    );
  }, [handleRowClick, handleEdit, handleDeleteClick]);

  // ===== 테이블 헤더 액션 (5개 필터) =====
  const tableHeaderActions = (
    <div className="flex items-center gap-2 flex-wrap">
      {/* 구분 필터 */}
      <Select value={categoryFilter} onValueChange={setCategoryFilter}>
        <SelectTrigger className="w-[120px]">
          <SelectValue placeholder="구분" />
        </SelectTrigger>
        <SelectContent>
          {VENDOR_CATEGORY_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      {/* 신용등급 필터 */}
      <Select value={creditRatingFilter} onValueChange={setCreditRatingFilter}>
        <SelectTrigger className="w-[110px]">
          <SelectValue placeholder="신용등급" />
        </SelectTrigger>
        <SelectContent>
          {CREDIT_RATING_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      {/* 거래등급 필터 */}
      <Select value={transactionGradeFilter} onValueChange={setTransactionGradeFilter}>
        <SelectTrigger className="w-[120px]">
          <SelectValue placeholder="거래등급" />
        </SelectTrigger>
        <SelectContent>
          {TRANSACTION_GRADE_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      {/* 악성채권 필터 */}
      <Select value={badDebtFilter} onValueChange={setBadDebtFilter}>
        <SelectTrigger className="w-[110px]">
          <SelectValue placeholder="악성채권" />
        </SelectTrigger>
        <SelectContent>
          {BAD_DEBT_STATUS_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-[150px]">
          <SelectValue placeholder="정렬" />
        </SelectTrigger>
        <SelectContent>
          {SORT_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );

  return (
    <>
      <IntegratedListTemplateV2
        title="거래처관리"
        description="거래처 정보를 등록하고 관리합니다"
        icon={Building2}
        stats={statCards}
        searchValue={searchQuery}
        onSearchChange={setSearchQuery}
        searchPlaceholder="거래처명, 거래처코드, 사업자번호 검색..."
        tableHeaderActions={tableHeaderActions}
        tableColumns={tableColumns}
        data={paginatedData}
        totalCount={filteredData.length}
        allData={filteredData}
        selectedItems={selectedItems}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        getItemId={(item: Vendor) => 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>
    </>
  );
}