'use client';

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { format } from 'date-fns';
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 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';

// ===== Mock 데이터 생성 =====
const generateMockData = (): BillRecord[] => {
  const billTypes: BillType[] = ['received', 'issued'];
  const receivedStatuses: BillStatus[] = ['stored', 'maturityAlert', 'maturityResult', 'paymentComplete', 'dishonored'];
  const issuedStatuses: BillStatus[] = ['stored', 'maturityAlert', 'collectionRequest', 'collectionComplete', 'suing', 'dishonored'];
  const vendors = ['(주)삼성전자', '현대자동차', 'LG전자', 'SK하이닉스', '네이버', '카카오'];
  const amounts = [10000000, 25000000, 5000000, 30000000, 15000000, 8000000, 40000000, 100000000];

  return Array.from({ length: 50 }, (_, i) => {
    const billType = billTypes[i % billTypes.length];
    const statuses = billType === 'received' ? receivedStatuses : issuedStatuses;
    const amount = amounts[i % amounts.length] + (i * 1000000);

    return {
      id: `bill-${i + 1}`,
      billNumber: `2025${String(i + 1).padStart(6, '0')}`,
      billType,
      vendorId: `vendor-${i % vendors.length}`,
      vendorName: vendors[i % vendors.length],
      amount,
      issueDate: format(new Date(2025, 11, (i % 17) + 1), 'yyyy-MM-dd'),
      maturityDate: format(new Date(2025, 11, (i % 17) + 15), 'yyyy-MM-dd'),
      status: statuses[i % statuses.length],
      reason: i % 3 === 0 ? '거래 대금' : '',
      installmentCount: i % 5,
      note: i % 4 === 0 ? '메모 내용' : '',
      installments: [],
      createdAt: '2025-12-18T00:00:00.000Z',
      updatedAt: '2025-12-18T00:00:00.000Z',
    };
  });
};

interface BillManagementProps {
  initialVendorId?: string;
  initialBillType?: string;
}

export function BillManagement({ initialVendorId, initialBillType }: BillManagementProps = {}) {
  const router = useRouter();

  // ===== 상태 관리 =====
  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(1);
  const itemsPerPage = 20;

  // 삭제 다이얼로그
  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');

  // Mock 데이터
  const [data, setData] = useState<BillRecord[]>(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.billNumber.includes(searchQuery) ||
      item.vendorName.includes(searchQuery) ||
      item.note.includes(searchQuery)
    );

    // 거래처 필터 (vendorId 또는 vendorName으로 필터링)
    if (vendorFilter !== 'all') {
      result = result.filter(item =>
        item.vendorId === vendorFilter || item.vendorName === vendorFilter
      );
    }

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

    // 상태 필터 (보관중 등)
    if (statusFilter !== 'all') {
      result = result.filter(item => item.status === statusFilter);
    }

    // 정렬
    switch (sortOption) {
      case 'latest':
        result.sort((a, b) => new Date(b.issueDate).getTime() - new Date(a.issueDate).getTime());
        break;
      case 'oldest':
        result.sort((a, b) => new Date(a.issueDate).getTime() - new Date(b.issueDate).getTime());
        break;
      case 'amountHigh':
        result.sort((a, b) => b.amount - a.amount);
        break;
      case 'amountLow':
        result.sort((a, b) => a.amount - b.amount);
        break;
      case 'maturityDate':
        result.sort((a, b) => new Date(a.maturityDate).getTime() - new Date(b.maturityDate).getTime());
        break;
    }

    return result;
  }, [data, searchQuery, vendorFilter, billTypeFilter, statusFilter, 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: BillRecord) => {
    router.push(`/ko/accounting/bills/${item.id}`);
  }, [router]);

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

  const handleConfirmDelete = useCallback(() => {
    if (deleteTargetId) {
      console.log('삭제:', 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 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]);

  // ===== 헤더 액션 (매출관리와 동일한 패턴: DateRangeSelector + extraActions) =====
  const headerActions = (
    <DateRangeSelector
      startDate={startDate}
      endDate={endDate}
      onStartDateChange={setStartDate}
      onEndDateChange={setEndDate}
      extraActions={
        <Button 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={setBillTypeFilter}>
        <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={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>
    </div>
  );

  // ===== 저장 핸들러 =====
  const handleSave = useCallback(() => {
    if (selectedItems.size === 0) {
      console.log('선택된 항목이 없습니다.');
      return;
    }
    console.log('저장:', Array.from(selectedItems), '상태:', statusFilter, '구분:', billTypeFilter);
    // TODO: API 호출로 저장
  }, [selectedItems, statusFilter, billTypeFilter]);

  // ===== 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">
        <Save className="h-4 w-4 mr-2" />
        저장
      </Button>

      {/* 수취/발행 라디오 버튼 */}
      <RadioGroup
        value={billTypeFilter}
        onValueChange={setBillTypeFilter}
        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={paginatedData}
        totalCount={filteredData.length}
        allData={filteredData}
        selectedItems={selectedItems}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        getItemId={(item: BillRecord) => 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>
    </>
  );
}
