'use client';

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
  FileText,
  Plus,
  Pencil,
  Trash2,
  Save,
} 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 { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Label } from '@/components/ui/label';
import {
  IntegratedListTemplateV2,
  type TableColumn,
} from '@/components/templates/IntegratedListTemplateV2';
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { toast } from 'sonner';
import type {
  BillRecord,
  BillType,
  BillStatus,
  SortOption,
} from './types';
import {
  BILL_TYPE_LABELS,
  BILL_TYPE_FILTER_OPTIONS,
  BILL_STATUS_COLORS,
  BILL_STATUS_FILTER_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, setSortOption] = useState<SortOption>('latest');
  const [billTypeFilter, setBillTypeFilter] = useState<string>(initialBillType || 'received');
  const [vendorFilter, setVendorFilter] = useState<string>(initialVendorId || 'all');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(initialPagination.currentPage);
  const itemsPerPage = initialPagination.perPage;

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

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

  // ===== 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) {
        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 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}`);
  }, [router]);

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

  const handleConfirmDelete = useCallback(async () => {
    if (deleteTargetId) {
      setIsLoading(true);
      const result = await deleteBill(deleteTargetId);

      if (result.success) {
        setData(prev => prev.filter(item => item.id !== deleteTargetId));
        setSelectedItems(prev => {
          const newSet = new Set(prev);
          newSet.delete(deleteTargetId);
          return newSet;
        });
        toast.success('삭제되었습니다.');
      } else {
        toast.error(result.error || '삭제에 실패했습니다.');
      }
      setIsLoading(false);
    }
    setShowDeleteDialog(false);
    setDeleteTargetId(null);
  }, [deleteTargetId]);

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

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

  // ===== 테이블 행 렌더링 =====
  const renderTableRow = useCallback((item: BillRecord, 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">{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">{item.amount.toLocaleString()}</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>
        <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/bills/${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, router]);

  // ===== 모바일 카드 렌더링 =====
  const renderMobileCard = useCallback((
    item: BillRecord,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => {
    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={isSelected}
        onToggleSelection={onToggle}
        infoGrid={
          <div className="grid grid-cols-2 gap-3">
            <InfoField label="거래처" value={item.vendorName} />
            <InfoField label="금액" value={`${item.amount.toLocaleString()}원`} />
            <InfoField label="발행일" value={item.issueDate} />
            <InfoField label="만기일" value={item.maturityDate} />
          </div>
        }
        actions={
          isSelected ? (
            <div className="flex gap-2 w-full">
              <Button variant="outline" className="flex-1" onClick={() => router.push(`/ko/accounting/bills/${item.id}?mode=edit`)}>
                <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, router]);

  // ===== 헤더 액션 =====
  const headerActions = (
    <>
      <DateRangeSelector
        startDate={startDate}
        endDate={endDate}
        onStartDateChange={setStartDate}
        onEndDateChange={setEndDate}
      />
      <Button className="ml-auto" onClick={() => router.push('/ko/accounting/bills/new')}>
        <Plus className="h-4 w-4 mr-2" />
        어음 등록
      </Button>
    </>
  );

  // ===== 거래처 목록 (필터용) =====
  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-[120px]">
          <SelectValue placeholder="거래처명" />
        </SelectTrigger>
        <SelectContent>
          {vendorOptions.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      <Select value={billTypeFilter} onValueChange={(value) => { setBillTypeFilter(value); loadData(1); }}>
        <SelectTrigger className="w-[100px]">
          <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={(value) => { setStatusFilter(value); loadData(1); }}>
        <SelectTrigger className="w-[110px]">
          <SelectValue placeholder="보관중" />
        </SelectTrigger>
        <SelectContent>
          {BILL_STATUS_FILTER_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );

  // ===== 저장 핸들러 =====
  const handleSave = useCallback(async () => {
    if (selectedItems.size === 0) {
      toast.warning('선택된 항목이 없습니다.');
      return;
    }

    if (statusFilter === 'all') {
      toast.warning('상태를 선택해주세요.');
      return;
    }

    setIsLoading(true);
    let successCount = 0;

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

    if (successCount > 0) {
      toast.success(`${successCount}건이 저장되었습니다.`);
      loadData(currentPage);
      setSelectedItems(new Set());
    } else {
      toast.error('저장에 실패했습니다.');
    }
    setIsLoading(false);
  }, [selectedItems, statusFilter, loadData, currentPage]);

  // ===== beforeTableContent =====
  const billStatusSelector = (
    <div className="flex items-center gap-4">
      <Select value={statusFilter} onValueChange={setStatusFilter}>
        <SelectTrigger className="w-[110px]">
          <SelectValue placeholder="보관중" />
        </SelectTrigger>
        <SelectContent>
          {BILL_STATUS_FILTER_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      <Button onClick={handleSave} className="bg-orange-500 hover:bg-orange-600" disabled={isLoading}>
        <Save className="h-4 w-4 mr-2" />
        저장
      </Button>

      <RadioGroup
        value={billTypeFilter}
        onValueChange={(value) => { setBillTypeFilter(value); loadData(1); }}
        className="flex items-center gap-4"
      >
        <div className="flex items-center space-x-2">
          <RadioGroupItem value="received" id="received" />
          <Label htmlFor="received" className="cursor-pointer">수취</Label>
        </div>
        <div className="flex items-center space-x-2">
          <RadioGroupItem value="issued" id="issued" />
          <Label htmlFor="issued" className="cursor-pointer">발행</Label>
        </div>
      </RadioGroup>
    </div>
  );

  return (
    <>
      <IntegratedListTemplateV2
        title="어음관리"
        description="어음 및 수취이음 상세 현황을 관리합니다"
        icon={FileText}
        headerActions={headerActions}
        searchValue={searchQuery}
        onSearchChange={setSearchQuery}
        searchPlaceholder="어음번호, 거래처, 메모 검색..."
        beforeTableContent={billStatusSelector}
        tableHeaderActions={tableHeaderActions}
        tableColumns={tableColumns}
        data={data}
        totalCount={pagination.total}
        allData={data}
        selectedItems={selectedItems}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        getItemId={(item: BillRecord) => item.id}
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        pagination={{
          currentPage: pagination.currentPage,
          totalPages: pagination.lastPage,
          totalItems: pagination.total,
          itemsPerPage: pagination.perPage,
          onPageChange: handlePageChange,
        }}
      />

      <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>
    </>
  );
}
