'use client';

/**
 * 어음관리 - UniversalListPage 마이그레이션
 *
 * IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 서버 사이드 필터링/페이지네이션
 * - dateRangeSelector + 등록 버튼 (headerActions)
 * - beforeTableContent: 상태 선택 + 저장 버튼 + 수취/발행 라디오
 * - tableHeaderActions: 거래처, 구분, 상태 필터
 */

import { useState, useMemo, useCallback, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { formatNumber } from '@/lib/utils/amount';
import { useDateRange } from '@/hooks';
import {
  FileText,
  Plus,
  RefreshCw,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { invalidateDashboard } from '@/lib/dashboard-invalidation';
import { TableRow, TableCell } from '@/components/ui/table';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  UniversalListPage,
  type UniversalListConfig,
  type TableColumn,
  type SelectionHandlers,
  type RowClickHandlers,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { toast } from 'sonner';
import type {
  BillRecord,
  BillStatus,
  SortOption,
} from './types';
import {
  BILL_TYPE_LABELS,
  BILL_TYPE_FILTER_OPTIONS,
  BILL_STATUS_COLORS,
  BILL_STATUS_FILTER_OPTIONS,
  RECEIVED_BILL_STATUS_OPTIONS,
  ISSUED_BILL_STATUS_OPTIONS,
  getBillStatusLabel,
} from './types';
import { getBills, deleteBill, updateBillStatus } from './actions';

interface BillManagementClientProps {
  initialData: BillRecord[];
  initialPagination: {
    currentPage: number;
    lastPage: number;
    perPage: number;
    total: number;
  };
  initialVendorId?: string;
  initialBillType?: string;
}

export function BillManagementClient({
  initialData,
  initialPagination,
  initialVendorId,
  initialBillType,
}: BillManagementClientProps) {
  const router = useRouter();

  // ===== 상태 관리 =====
  const [data, setData] = useState<BillRecord[]>(initialData);
  const [pagination, setPagination] = useState(initialPagination);
  const [isLoading, setIsLoading] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortOption] = useState<SortOption>('latest');
  const [billTypeFilter, setBillTypeFilter] = useState<string>(initialBillType || 'received');
  const [vendorFilter, setVendorFilter] = useState<string>(initialVendorId || 'all');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [targetStatus, setTargetStatus] = useState<string>('');
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(initialPagination.currentPage);
  const itemsPerPage = initialPagination.perPage;

  // 날짜 범위 상태
  const { startDate, endDate, setStartDate, setEndDate } = useDateRange('currentYear');

  // ===== API 데이터 로드 =====
  const loadData = useCallback(async (page: number = 1) => {
    setIsLoading(true);
    try {
      const result = await getBills({
        search: searchQuery || undefined,
        billType: billTypeFilter !== 'all' ? billTypeFilter : undefined,
        status: statusFilter !== 'all' ? statusFilter : undefined,
        clientId: vendorFilter !== 'all' ? vendorFilter : undefined,
        issueStartDate: startDate,
        issueEndDate: endDate,
        sortBy: sortOption === 'latest' || sortOption === 'oldest' ? 'issue_date' : sortOption === 'amountHigh' || sortOption === 'amountLow' ? 'amount' : 'maturity_date',
        sortDir: sortOption === 'oldest' || sortOption === 'amountLow' ? 'asc' : 'desc',
        perPage: itemsPerPage,
        page,
      });

      if (result.success) {
        // 삭제 후 현재 페이지가 빈 페이지가 되면 마지막 유효 페이지로 이동
        if (result.data.length === 0 && result.pagination.lastPage > 0 && page > result.pagination.lastPage) {
          loadData(result.pagination.lastPage);
          return;
        }
        setData(result.data);
        setPagination(result.pagination);
        setCurrentPage(result.pagination.currentPage);
      } else {
        toast.error(result.error || '데이터를 불러오는데 실패했습니다.');
      }
    } catch {
      toast.error('데이터를 불러오는데 실패했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, [searchQuery, billTypeFilter, statusFilter, vendorFilter, startDate, endDate, sortOption, itemsPerPage]);

  // ===== 필터 변경 시 자동 재조회 =====
  const isInitialMount = useRef(true);
  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;
      return;
    }
    loadData(1);
  }, [loadData]);

  // ===== 체크박스 핸들러 =====
  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 toggleSelectAll = useCallback(() => {
    if (selectedItems.size === data.length && data.length > 0) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(data.map(item => item.id)));
    }
  }, [selectedItems.size, data]);

  // ===== 액션 핸들러 =====
  const handleRowClick = useCallback((item: BillRecord) => {
    router.push(`/ko/accounting/bills/${item.id}?mode=view`);
  }, [router]);


  // ===== 페이지 변경 =====
  const handlePageChange = useCallback((page: number) => {
    loadData(page);
  }, [loadData]);

  // ===== 테이블 컬럼 =====
  const tableColumns: TableColumn[] = useMemo(() => [
    { key: 'no', label: '번호', className: 'text-center w-[60px]' },
    { key: 'billNumber', label: '어음번호', sortable: true, copyable: true },
    { key: 'billType', label: '구분', className: 'text-center', sortable: true },
    { key: 'vendorName', label: '거래처', sortable: true, copyable: true },
    { key: 'amount', label: '금액', className: 'text-right', sortable: true, copyable: true },
    { key: 'issueDate', label: '발행일', sortable: true, copyable: true },
    { key: 'maturityDate', label: '만기일', sortable: true, copyable: true },
    { key: 'installmentCount', label: '차수', className: 'text-center', sortable: true, copyable: true },
    { key: 'status', label: '상태', className: 'text-center', sortable: true },
  ], []);

  // ===== 테이블 행 렌더링 =====
  const renderTableRow = useCallback((
    item: BillRecord,
    index: number,
    globalIndex: number,
    handlers: SelectionHandlers & RowClickHandlers<BillRecord>
  ) => {
    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-center">{globalIndex}</TableCell>
        <TableCell>{item.billNumber}</TableCell>
        <TableCell className="text-center">
          <Badge variant="outline" className={item.billType === 'received' ? 'border-blue-300 text-blue-600' : 'border-green-300 text-green-600'}>
            {BILL_TYPE_LABELS[item.billType]}
          </Badge>
        </TableCell>
        <TableCell>{item.vendorName}</TableCell>
        <TableCell className="text-right font-medium">{formatNumber(item.amount)}</TableCell>
        <TableCell>{item.issueDate}</TableCell>
        <TableCell>{item.maturityDate}</TableCell>
        <TableCell className="text-center">{item.installmentCount || '-'}</TableCell>
        <TableCell className="text-center">
          <Badge className={BILL_STATUS_COLORS[item.status]}>
            {getBillStatusLabel(item.billType, item.status)}
          </Badge>
        </TableCell>
      </TableRow>
    );
  }, [handleRowClick]);

  // ===== 모바일 카드 렌더링 =====
  const renderMobileCard = useCallback((
    item: BillRecord,
    index: number,
    globalIndex: number,
    handlers: SelectionHandlers & RowClickHandlers<BillRecord>
  ) => {
    return (
      <ListMobileCard
        id={item.id}
        title={item.billNumber}
        headerBadges={
          <>
            <Badge variant="outline" className={item.billType === 'received' ? 'border-blue-300 text-blue-600' : 'border-green-300 text-green-600'}>
              {BILL_TYPE_LABELS[item.billType]}
            </Badge>
            <Badge className={BILL_STATUS_COLORS[item.status]}>
              {getBillStatusLabel(item.billType, item.status)}
            </Badge>
          </>
        }
        isSelected={handlers.isSelected}
        onToggleSelection={handlers.onToggle}
        infoGrid={
          <div className="grid grid-cols-1 gap-2">
            <InfoField label="거래처" value={item.vendorName} />
            <InfoField label="금액" value={`${formatNumber(item.amount)}원`} />
            <InfoField label="발행일" value={item.issueDate} />
            <InfoField label="만기일" value={item.maturityDate} />
          </div>
        }
        onCardClick={() => handleRowClick(item)}
      />
    );
  }, [handleRowClick]);

  // ===== 거래처 목록 (필터용) =====
  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 handleStatusChange = useCallback(async () => {
    if (selectedItems.size === 0) {
      toast.warning('선택된 항목이 없습니다.');
      return;
    }

    if (!targetStatus) {
      toast.warning('변경할 상태를 선택해주세요.');
      return;
    }

    setIsLoading(true);
    let successCount = 0;

    for (const id of selectedItems) {
      const result = await updateBillStatus(id, targetStatus as BillStatus);
      if (result.success) {
        successCount++;
      }
    }

    if (successCount > 0) {
      invalidateDashboard('bill');
      toast.success(`${successCount}건의 상태가 변경되었습니다.`);
      loadData(currentPage);
      setSelectedItems(new Set());
      setTargetStatus('');
    } else {
      toast.error('상태 변경에 실패했습니다.');
    }
    setIsLoading(false);
  }, [selectedItems, targetStatus, loadData, currentPage]);

  // 구분에 따른 상태 옵션
  const statusChangeOptions = useMemo(() => {
    return billTypeFilter === 'issued' ? ISSUED_BILL_STATUS_OPTIONS : RECEIVED_BILL_STATUS_OPTIONS;
  }, [billTypeFilter]);

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<BillRecord> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '어음관리',
      description: '어음 및 수취이음 상세 현황을 관리합니다',
      icon: FileText,
      basePath: '/accounting/bills',

      // ID 추출
      idField: 'id',

      // API 액션
      actions: {
        getList: async () => {
          return {
            success: true,
            data: data,
            totalCount: pagination.total,
          };
        },
        deleteItem: async (id: string) => {
          const result = await deleteBill(id);
          if (result.success) {
            invalidateDashboard('bill');
            await loadData(currentPage);
            setSelectedItems(prev => {
              const newSet = new Set(prev);
              newSet.delete(id);
              return newSet;
            });
          }
          return { success: result.success, error: result.error };
        },
      },

      // 삭제 확인 메시지
      deleteConfirmMessage: {
        title: '어음 삭제',
        description: '이 어음을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.',
      },

      // 테이블 컬럼
      columns: tableColumns,

      // 서버 사이드 필터링
      clientSideFiltering: false,
      itemsPerPage: pagination.perPage,

      // 검색
      searchPlaceholder: '어음번호, 거래처, 메모 검색...',
      onSearchChange: setSearchQuery,
      searchFilter: (item: BillRecord, search: string) => {
        const s = search.toLowerCase();
        return (
          item.billNumber?.toLowerCase().includes(s) ||
          item.vendorName?.toLowerCase().includes(s) ||
          item.note?.toLowerCase().includes(s) ||
          false
        );
      },

      // 모바일 필터 설정 (tableHeaderActions와 중복 방지를 위해 비워둠)
      filterConfig: [],
      filterTitle: '어음 필터',

      // 날짜 선택기
      dateRangeSelector: {
        enabled: true,
        startDate,
        endDate,
        onStartDateChange: setStartDate,
        onEndDateChange: setEndDate,
      },

      // 등록 버튼
      createButton: {
        label: '어음 등록',
        onClick: () => router.push('/ko/accounting/bills?mode=new'),
        icon: Plus,
      },

      // 선택 시 상태 변경 액션
      selectionActions: () => (
        <div className="flex items-center gap-2">
          <Select value={targetStatus} onValueChange={setTargetStatus}>
            <SelectTrigger className="min-w-[130px] w-auto h-8">
              <SelectValue placeholder="상태 선택" />
            </SelectTrigger>
            <SelectContent>
              {statusChangeOptions.map((option) => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Button
            size="sm"
            onClick={handleStatusChange}
            disabled={!targetStatus || isLoading}
          >
            <RefreshCw className="h-4 w-4 mr-1" />
            상태변경
          </Button>
        </div>
      ),

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

          <Select value={billTypeFilter} onValueChange={setBillTypeFilter}>
            <SelectTrigger className="min-w-[100px] w-auto">
              <SelectValue placeholder="구분" />
            </SelectTrigger>
            <SelectContent>
              {BILL_TYPE_FILTER_OPTIONS.map((option) => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="min-w-[110px] w-auto">
              <SelectValue placeholder="보관중" />
            </SelectTrigger>
            <SelectContent>
              {BILL_STATUS_FILTER_OPTIONS.map((option) => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      ),

      // 렌더링 함수
      renderTableRow,
      renderMobileCard,
    }),
    [
      data,
      pagination,
      tableColumns,
      startDate,
      endDate,
      vendorFilter,
      vendorOptions,
      billTypeFilter,
      statusFilter,
      isLoading,
      router,
      loadData,
      currentPage,
      handleStatusChange,
      statusChangeOptions,
      targetStatus,
      renderTableRow,
      renderMobileCard,
    ]
  );

  return (
    <>
      <UniversalListPage
        config={config}
        initialData={data}
        externalPagination={{
          currentPage: pagination.currentPage,
          totalPages: pagination.lastPage,
          totalItems: pagination.total,
          itemsPerPage: pagination.perPage,
          onPageChange: handlePageChange,
        }}
        externalSelection={{
          selectedItems,
          onToggleSelection: toggleSelection,
          onToggleSelectAll: toggleSelectAll,
          getItemId: (item: BillRecord) => item.id,
        }}
      />

    </>
  );
}
