'use client'

import * as React from 'react'
import { type DataTableAdvancedFilterField, type DataTableFilterField } from '@/types/table'
import { useDataTable } from '@/hooks/use-data-table'
import { DataTable } from '@/components/data-table/data-table'
import { DataTableAdvancedToolbar } from '@/components/data-table/data-table-advanced-toolbar'
import { BiddingPreQuoteVendorToolbarActions } from './bidding-pre-quote-vendor-toolbar-actions'
import { BiddingPreQuoteVendorEditDialog } from './bidding-pre-quote-vendor-edit-dialog'
import { getBiddingPreQuoteVendorColumns, BiddingCompany } from './bidding-pre-quote-vendor-columns'
import { Bidding } from '@/db/schema'
import {
  deleteBiddingCompany
} from '../service'
import { getPriceAdjustmentFormByBiddingCompanyId } from '@/lib/bidding/detail/service'
import { useToast } from '@/hooks/use-toast'
import { useTransition } from 'react'
import { PriceAdjustmentDialog } from '@/components/bidding/price-adjustment-dialog'
import { BiddingPreQuoteItemDetailsDialog } from './bidding-pre-quote-item-details-dialog'
import { BiddingPreQuoteAttachmentsDialog } from './bidding-pre-quote-attachments-dialog'
import { getPrItemsForBidding } from '../service'

interface BiddingPreQuoteVendorTableContentProps {
  biddingId: number
  bidding: Bidding
  biddingCompanies: BiddingCompany[]
  onRefresh: () => void
  onOpenItemsDialog: () => void
  onOpenTargetPriceDialog: () => void
  onOpenSelectionReasonDialog: () => void
  onEdit?: (company: BiddingCompany) => void
  onDelete?: (company: BiddingCompany) => void
}

const filterFields: DataTableFilterField<BiddingCompany>[] = [
  {
    id: 'companyName',
    label: '업체명',
    placeholder: '업체명으로 검색...',
  },
  {
    id: 'companyCode',
    label: '업체코드',
    placeholder: '업체코드로 검색...',
  },
  {
    id: 'contactPerson',
    label: '담당자',
    placeholder: '담당자로 검색...',
  },
]

const advancedFilterFields: DataTableAdvancedFilterField<BiddingCompany>[] = [
  {
    id: 'companyName',
    label: '업체명',
    type: 'text',
  },
  {
    id: 'companyCode',
    label: '업체코드',
    type: 'text',
  },
  {
    id: 'contactPerson',
    label: '담당자',
    type: 'text',
  },
  {
    id: 'preQuoteAmount',
    label: '사전견적금액',
    type: 'number',
  },
  {
    id: 'invitationStatus',
    label: '초대 상태',
    type: 'multi-select',
    options: [
      { label: '수락', value: 'accepted' },
      { label: '거절', value: 'declined' },
      { label: '요청됨', value: 'sent' },
      { label: '대기중', value: 'pending' },
    ],
  },
]

export function BiddingPreQuoteVendorTableContent({
  biddingId,
  bidding,
  biddingCompanies,
  onRefresh,
  onOpenItemsDialog,
  onOpenTargetPriceDialog,
  onOpenSelectionReasonDialog,
  onEdit,
  onDelete
}: BiddingPreQuoteVendorTableContentProps) {
  const { toast } = useToast()
  const [isPending, startTransition] = useTransition()
  const [selectedCompany, setSelectedCompany] = React.useState<BiddingCompany | null>(null)
  const [isEditDialogOpen, setIsEditDialogOpen] = React.useState(false)
  const [isPriceAdjustmentDialogOpen, setIsPriceAdjustmentDialogOpen] = React.useState(false)
  const [priceAdjustmentData, setPriceAdjustmentData] = React.useState<any>(null)
  const [isItemDetailsDialogOpen, setIsItemDetailsDialogOpen] = React.useState(false)
  const [selectedCompanyForDetails, setSelectedCompanyForDetails] = React.useState<BiddingCompany | null>(null)
  const [prItems, setPrItems] = React.useState<any[]>([])
  const [isAttachmentsDialogOpen, setIsAttachmentsDialogOpen] = React.useState(false)
  const [selectedCompanyForAttachments, setSelectedCompanyForAttachments] = React.useState<BiddingCompany | null>(null)

  const handleDelete = (company: BiddingCompany) => {
    startTransition(async () => {
      const response = await deleteBiddingCompany(company.id)

      if (response.success) {
        toast({
          title: '성공',
          description: response.message,
        })
        onRefresh()
      } else {
        toast({
          title: '오류',
          description: response.error,
          variant: 'destructive',
        })
      }
    })
  }

  const handleEdit = (company: BiddingCompany) => {
    setSelectedCompany(company)
    setIsEditDialogOpen(true)
  }


  const handleViewPriceAdjustment = async (company: BiddingCompany) => {
    startTransition(async () => {
      const priceAdjustmentForm = await getPriceAdjustmentFormByBiddingCompanyId(company.id)
      if (priceAdjustmentForm) {
        setPriceAdjustmentData(priceAdjustmentForm)
        setSelectedCompany(company)
        setIsPriceAdjustmentDialogOpen(true)
      } else {
        toast({
          title: '정보 없음',
          description: '연동제 정보가 없습니다.',
          variant: 'destructive',
        })
      }
    })
  }

  const handleViewItemDetails = async (company: BiddingCompany) => {
    startTransition(async () => {
      try {
        // PR 아이템 정보 로드
        const prItemsData = await getPrItemsForBidding(biddingId)
        setPrItems(prItemsData)
        setSelectedCompanyForDetails(company)
        setIsItemDetailsDialogOpen(true)
      } catch (error) {
        console.error('Failed to load PR items:', error)
        toast({
          title: '오류',
          description: '품목 정보를 불러오는데 실패했습니다.',
          variant: 'destructive',
        })
      }
    })
  }

  const handleViewAttachments = (company: BiddingCompany) => {
    setSelectedCompanyForAttachments(company)
    setIsAttachmentsDialogOpen(true)
  }

  const columns = React.useMemo(
    () => getBiddingPreQuoteVendorColumns({
      onEdit: onEdit || handleEdit,
      onDelete: onDelete || handleDelete,
      onViewPriceAdjustment: handleViewPriceAdjustment,
      onViewItemDetails: handleViewItemDetails,
      onViewAttachments: handleViewAttachments
    }),
    [onEdit, onDelete, handleEdit, handleDelete, handleViewPriceAdjustment, handleViewItemDetails, handleViewAttachments]
  )

  const { table } = useDataTable({
    data: biddingCompanies,
    columns,
    pageCount: 1,
    filterFields,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: 'companyName', desc: false }],
      columnPinning: { right: ['actions'] },
    },
    getRowId: (originalRow) => originalRow.id.toString(),
    shallow: false,
    clearOnDefault: true,
  })

  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <BiddingPreQuoteVendorToolbarActions
            table={table}
            biddingId={biddingId}
            bidding={bidding}
            biddingCompanies={biddingCompanies}
            onOpenItemsDialog={onOpenItemsDialog}
            onOpenTargetPriceDialog={onOpenTargetPriceDialog}
            onOpenSelectionReasonDialog={onOpenSelectionReasonDialog}
            onSuccess={onRefresh}
          />
        </DataTableAdvancedToolbar>
      </DataTable>

      <BiddingPreQuoteVendorEditDialog
        company={selectedCompany}
        open={isEditDialogOpen}
        onOpenChange={setIsEditDialogOpen}
        onSuccess={onRefresh}
      />

      <PriceAdjustmentDialog
        open={isPriceAdjustmentDialogOpen}
        onOpenChange={setIsPriceAdjustmentDialogOpen}
        data={priceAdjustmentData}
        vendorName={selectedCompany?.companyName || ''}
      />

      <BiddingPreQuoteItemDetailsDialog
        open={isItemDetailsDialogOpen}
        onOpenChange={setIsItemDetailsDialogOpen}
        biddingId={biddingId}
        biddingCompanyId={selectedCompanyForDetails?.id || 0}
        companyName={selectedCompanyForDetails?.companyName || ''}
        prItems={prItems}
        currency={bidding.currency || 'KRW'}
      />

      <BiddingPreQuoteAttachmentsDialog
        open={isAttachmentsDialogOpen}
        onOpenChange={setIsAttachmentsDialogOpen}
        biddingId={biddingId}
        companyId={selectedCompanyForAttachments?.companyId || 0}
        companyName={selectedCompanyForAttachments?.companyName || ''}
      />
    </>
  )
}
