'use client';

/**
 * 경조사비 관리 - 목록 페이지
 *
 * UniversalListPage + clientSideFiltering 패턴 (품목관리와 동일)
 * - 통계카드 (총건수/총금액/부조금합계/선물합계)
 * - 필터: 연도 Select, 구분 filterConfig, 검색 (클라이언트 사이드)
 * - 테이블 + 등록/수정 모달
 */

import { useState, useEffect, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import {
  Heart,
  DollarSign,
  Banknote,
  Gift,
  Trash2,
  Loader2,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { BadgeSm } from '@/components/atoms/BadgeSm';
import {
  UniversalListPage,
  type UniversalListConfig,
  type TableColumn,
  type FilterFieldConfig,
} from '@/components/templates/UniversalListPage';
import { toast } from 'sonner';
import { TableRow, TableCell } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import { formatAmount } from '@/lib/utils/amount';
import {
  getCondolenceExpenses,
  getCondolenceExpenseSummary,
  deleteCondolenceExpense,
} from './actions';
import { CondolenceExpenseFormModal } from './CondolenceExpenseForm';
import {
  CATEGORY_BADGE,
  CATEGORY_OPTIONS,
  type CondolenceExpense,
  type CondolenceExpenseSummary,
} from './types';

// 연도 옵션 (당해 ~ 5년 전)
function getYearOptions() {
  const currentYear = new Date().getFullYear();
  return Array.from({ length: 6 }, (_, i) => ({
    value: String(currentYear - i),
    label: `${currentYear - i}년`,
  }));
}

const BASE_PATH = '/accounting/condolence-expenses';

const tableColumns: TableColumn[] = [
  { key: 'no', label: '번호', className: 'text-center w-[50px]' },
  { key: 'event_date', label: '경조사일자', className: 'px-2 w-[100px]', sortable: true, copyable: true },
  { key: 'expense_date', label: '지출일자', className: 'px-2 w-[100px]', copyable: true },
  { key: 'partner_name', label: '거래처명', className: 'px-2', sortable: true, copyable: true },
  { key: 'description', label: '내역', className: 'px-2', copyable: true },
  { key: 'category', label: '구분', className: 'px-2 text-center w-[70px]' },
  { key: 'has_cash', label: '부조금', className: 'px-2 text-center w-[60px]' },
  { key: 'cash_method', label: '지출방법', className: 'px-2 w-[80px]' },
  { key: 'cash_amount', label: '부조금액', className: 'px-2 text-right w-[100px]' },
  { key: 'has_gift', label: '선물', className: 'px-2 text-center w-[60px]' },
  { key: 'gift_type', label: '선물종류', className: 'px-2 w-[80px]' },
  { key: 'gift_amount', label: '선물금액', className: 'px-2 text-right w-[100px]' },
  { key: 'total_amount', label: '총금액', className: 'px-2 text-right w-[100px]' },
  { key: 'memo', label: '비고', className: 'px-2' },
];

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

  // 연도 필터
  const [year, setYear] = useState<string>(String(new Date().getFullYear()));

  // 필터 (filterConfig)
  const [filterValues, setFilterValues] = useState<Record<string, string | string[]>>({
    category: 'all',
  });

  const filterConfig: FilterFieldConfig[] = [
    {
      key: 'category',
      label: '구분',
      type: 'single',
      options: CATEGORY_OPTIONS.map((o) => ({ value: o.value, label: o.label })),
      allOptionLabel: '전체 구분',
    },
  ];

  // 모달 상태
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [editingItem, setEditingItem] = useState<CondolenceExpense | null>(null);

  // 삭제 다이얼로그
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [deleteTargetId, setDeleteTargetId] = useState<number | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);

  // API 상태
  const [data, setData] = useState<CondolenceExpense[]>([]);
  const [summaryData, setSummaryData] = useState<CondolenceExpenseSummary | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // 선택
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());

  // 데이터 로드
  const loadData = useCallback(async () => {
    try {
      setIsLoading(true);
      const categoryFilter = filterValues.category as string;
      const [listResult, summaryResult] = await Promise.all([
        getCondolenceExpenses({
          year: year ? Number(year) : undefined,
          category: categoryFilter !== 'all' ? categoryFilter : undefined,
          per_page: 200,
        }),
        getCondolenceExpenseSummary({
          year: year ? Number(year) : undefined,
          category: categoryFilter !== 'all' ? categoryFilter : undefined,
        }),
      ]);

      if (listResult.success) {
        setData(listResult.data);
      } else {
        toast.error(listResult.error || '목록 조회 실패');
      }

      if (summaryResult.success && summaryResult.data) {
        setSummaryData(summaryResult.data as CondolenceExpenseSummary);
      }
    } catch {
      toast.error('데이터 로드 중 오류 발생');
    } finally {
      setIsLoading(false);
    }
  }, [year, filterValues]);

  useEffect(() => { loadData(); }, [loadData]);

  // 통계 카드
  const stats = useMemo(() => {
    const s = summaryData;
    return [
      { label: '총 건수', value: `${s?.total_count ?? 0}건`, icon: Heart, iconColor: 'text-red-600' },
      { label: '총 금액', value: formatAmount(s?.total_amount ?? 0), icon: DollarSign, iconColor: 'text-blue-600' },
      { label: '부조금 합계', value: formatAmount(s?.cash_total ?? 0), icon: Banknote, iconColor: 'text-green-600' },
      { label: '선물 합계', value: formatAmount(s?.gift_total ?? 0), icon: Gift, iconColor: 'text-purple-600' },
    ];
  }, [summaryData]);

  // 핸들러
  const handleCreate = () => { setEditingItem(null); setIsFormOpen(true); };
  const handleEdit = (item: CondolenceExpense) => { setEditingItem(item); setIsFormOpen(true); };
  const handleDelete = (id: number) => { setDeleteTargetId(id); setIsDeleteDialogOpen(true); };

  const handleConfirmDelete = async () => {
    if (!deleteTargetId) return;
    setIsDeleting(true);
    try {
      const result = await deleteCondolenceExpense(deleteTargetId);
      if (result.success) {
        toast.success('삭제되었습니다.');
        loadData();
      } else {
        toast.error(result.error || '삭제 실패');
      }
    } catch {
      toast.error('삭제 중 오류 발생');
    } finally {
      setIsDeleting(false);
      setIsDeleteDialogOpen(false);
      setDeleteTargetId(null);
    }
  };

  const handleFormSuccess = () => {
    setIsFormOpen(false);
    setEditingItem(null);
    loadData();
  };

  // 선택 핸들러
  const toggleSelection = (id: string) => {
    const next = new Set(selectedItems);
    next.has(id) ? next.delete(id) : next.add(id);
    setSelectedItems(next);
  };

  const toggleSelectAll = () => {
    if (selectedItems.size === data.length && data.length > 0) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(data.map((d) => String(d.id))));
    }
  };

  // 테이블 행
  const renderTableRow = (
    item: CondolenceExpense,
    _index: number,
    globalIndex: number,
    handlers: { isSelected: boolean; onToggle: () => void }
  ) => {
    const { isSelected, onToggle } = handlers;
    const badge = CATEGORY_BADGE[item.category];
    return (
      <TableRow
        key={item.id}
        className={`cursor-pointer hover:bg-muted/50 ${isSelected ? 'bg-blue-50' : ''}`}
        onClick={() => handleEdit(item)}
      >
        <TableCell onClick={(e) => e.stopPropagation()} className="text-center">
          <Checkbox checked={isSelected} onCheckedChange={onToggle} />
        </TableCell>
        <TableCell className="text-center">{globalIndex}</TableCell>
        <TableCell>{item.event_date || '-'}</TableCell>
        <TableCell>{item.expense_date || '-'}</TableCell>
        <TableCell>{item.partner_name}</TableCell>
        <TableCell>{item.description || '-'}</TableCell>
        <TableCell className="text-center">
          <BadgeSm className={badge.className}>{badge.label}</BadgeSm>
        </TableCell>
        <TableCell className="text-center">{item.has_cash ? '여' : '부'}</TableCell>
        <TableCell>{item.cash_method_label || '-'}</TableCell>
        <TableCell className="text-right">{item.has_cash ? formatAmount(item.cash_amount) : '-'}</TableCell>
        <TableCell className="text-center">{item.has_gift ? '여' : '부'}</TableCell>
        <TableCell>{item.gift_type || '-'}</TableCell>
        <TableCell className="text-right">{item.has_gift ? formatAmount(item.gift_amount) : '-'}</TableCell>
        <TableCell className="text-right font-bold">{formatAmount(item.total_amount)}</TableCell>
        <TableCell className="max-w-[100px] truncate">{item.memo || '-'}</TableCell>
      </TableRow>
    );
  };

  // 모바일 카드
  const renderMobileCard = (
    item: CondolenceExpense,
    _index: number,
    globalIndex: number,
    handlers: { isSelected: boolean; onToggle: () => void }
  ) => {
    const { isSelected, onToggle } = handlers;
    const badge = CATEGORY_BADGE[item.category];
    return (
      <ListMobileCard
        key={item.id}
        id={String(item.id)}
        isSelected={isSelected}
        onToggleSelection={onToggle}
        onCardClick={() => handleEdit(item)}
        headerBadges={
          <BadgeSm className={badge.className}>{badge.label}</BadgeSm>
        }
        title={item.partner_name}
        statusBadge={
          <span className="text-sm font-bold text-blue-700">{formatAmount(item.total_amount)}</span>
        }
        infoGrid={
          <div className="grid grid-cols-2 gap-x-4 gap-y-3">
            <InfoField label="경조사일" value={item.event_date || '-'} />
            <InfoField label="내역" value={item.description || '-'} />
            <InfoField label="부조금" value={item.has_cash ? formatAmount(item.cash_amount) : '-'} />
            <InfoField label="선물" value={item.has_gift ? `${item.gift_type} ${formatAmount(item.gift_amount)}` : '-'} />
          </div>
        }
      />
    );
  };

  // UniversalListPage config
  const config: UniversalListConfig<CondolenceExpense> = {
    title: '경조사비 관리',
    description: '거래처/임직원 경조사비 관리',
    icon: Heart,
    basePath: BASE_PATH,
    idField: 'id',

    actions: {
      getList: async () => ({
        success: true,
        data,
        totalCount: data.length,
      }),
      deleteItem: async (id) => {
        const result = await deleteCondolenceExpense(id);
        if (result.success) loadData();
        return result;
      },
    },

    columns: tableColumns,

    computeStats: () => stats,

    searchPlaceholder: '거래처명, 내역, 비고 검색...',

    // 연도 Select
    dateRangeSelector: {
      enabled: true,
      hideDateInputs: true,
      showPresets: false,
      extraActions: (
        <Select value={year} onValueChange={(v) => { setYear(v); }}>
          <SelectTrigger className="w-[120px]">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {getYearOptions().map((o) => (
              <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      ),
    },

    itemsPerPage: 50,

    // 클라이언트 사이드 필터링 (검색 깜빡임 없음)
    clientSideFiltering: true,

    searchFilter: (item, searchValue) => {
      const q = searchValue.toLowerCase();
      return (
        (item.partner_name || '').toLowerCase().includes(q) ||
        (item.description || '').toLowerCase().includes(q) ||
        (item.memo || '').toLowerCase().includes(q)
      );
    },

    // 구분 필터
    filterConfig,
    initialFilters: filterValues,
    filterTitle: '경조사비 필터',

    customFilterFn: (items, fv) => {
      const cat = fv.category as string;
      if (!cat || cat === 'all') return items;
      return items.filter((item) => item.category === cat);
    },

    // 등록 버튼
    headerActions: () => (
      <Button onClick={handleCreate}>
        <Heart className="w-4 h-4 mr-2" />
        등록
      </Button>
    ),

    renderTableRow,
    renderMobileCard,

    renderDialogs: () => (
      <DeleteConfirmDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
        onConfirm={handleConfirmDelete}
        title="경조사비 삭제"
        description="이 경조사비 항목을 삭제하시겠습니까?"
        loading={isDeleting}
      />
    ),
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
          <p className="text-muted-foreground">경조사비 목록을 불러오는 중...</p>
        </div>
      </div>
    );
  }

  return (
    <>
      <UniversalListPage<CondolenceExpense>
        config={config}
        initialData={data}
        initialTotalCount={data.length}
        externalSelection={{
          selectedItems,
          onToggleSelection: toggleSelection,
          onToggleSelectAll: toggleSelectAll,
          setSelectedItems,
          getItemId: (item) => String(item.id),
        }}
        onFilterChange={(newFilters) => {
          setFilterValues(newFilters);
        }}
      />

      {/* 등록/수정 모달 */}
      <CondolenceExpenseFormModal
        open={isFormOpen}
        onOpenChange={setIsFormOpen}
        editItem={editingItem}
        onSuccess={handleFormSuccess}
      />
    </>
  );
}
