"use client"

import { type Table } from "@tanstack/react-table"
import { toast } from "sonner"
import { useRouter } from "next/navigation"

import { Button } from "@/components/ui/button"
import { Mail, FileWarning, Scale, FileText } from "lucide-react"
import type { VendorRegularRegistration } from "@/config/vendorRegularRegistrationsColumnsConfig"
import { 
  sendMissingContractRequestEmails,
  sendAdditionalInfoRequestEmails,
  skipLegalReview,
  submitRegistrationRequest
} from "../service"
import { useState } from "react"
import { SkipReasonDialog } from "@/components/vendor-regular-registrations/skip-reason-dialog"
import { RegistrationRequestDialog } from "@/components/vendor-regular-registrations/registration-request-dialog"

interface VendorRegularRegistrationsTableToolbarActionsProps {
  table: Table<VendorRegularRegistration>
}

export function VendorRegularRegistrationsTableToolbarActions({
  table,
}: VendorRegularRegistrationsTableToolbarActionsProps) {
  const router = useRouter()
  const [syncLoading, setSyncLoading] = useState<{ 
    missingContract: boolean; 
    additionalInfo: boolean;
    legalSkip: boolean;
    registrationRequest: boolean;
  }>({
    missingContract: false,
    additionalInfo: false,
    legalSkip: false,
    registrationRequest: false,
  })

  const [skipDialogs, setSkipDialogs] = useState<{
    legalReview: boolean;
  }>({
    legalReview: false,
  })

  const [registrationRequestDialog, setRegistrationRequestDialog] = useState<{
    open: boolean;
    registration: VendorRegularRegistration | null;
  }>({
    open: false,
    registration: null,
  })

  const selectedRows = table.getFilteredSelectedRowModel().rows.map(row => row.original)



  const handleSendMissingContractRequest = async () => {
    if (selectedRows.length === 0) {
      toast.error("이메일을 발송할 업체를 선택해주세요.")
      return
    }

    setSyncLoading(prev => ({ ...prev, missingContract: true }))
    try {
      const vendorIds = selectedRows.map(row => row.vendorId)
      const result = await sendMissingContractRequestEmails(vendorIds)
      
      if (result.success) {
        toast.success(result.message)
      } else {
        toast.error(result.error)
      }
    } catch (error) {
      console.error("Error sending missing contract request:", error)
      toast.error("누락계약요청 이메일 발송 중 오류가 발생했습니다.")
    } finally {
      setSyncLoading(prev => ({ ...prev, missingContract: false }))
    }
  }

  const handleSendAdditionalInfoRequest = async () => {
    if (selectedRows.length === 0) {
      toast.error("이메일을 발송할 업체를 선택해주세요.")
      return
    }

    setSyncLoading(prev => ({ ...prev, additionalInfo: true }))
    try {
      const vendorIds = selectedRows.map(row => row.vendorId)
      const result = await sendAdditionalInfoRequestEmails(vendorIds)
      
      if (result.success) {
        toast.success(result.message)
      } else {
        toast.error(result.error)
      }
    } catch (error) {
      console.error("Error sending additional info request:", error)
      toast.error("추가정보요청 이메일 발송 중 오류가 발생했습니다.")
    } finally {
      setSyncLoading(prev => ({ ...prev, additionalInfo: false }))
    }
  }

  const handleLegalReviewSkip = async (reason: string) => {
    const cpReviewRows = selectedRows.filter(row => row.status === "cp_review");
    if (cpReviewRows.length === 0) {
      toast.error("CP검토 상태인 업체를 선택해주세요.");
      return;
    }

    setSyncLoading(prev => ({ ...prev, legalSkip: true }));
    try {
      const vendorIds = cpReviewRows.map(row => row.vendorId);
      const result = await skipLegalReview(vendorIds, reason);
      
      if (result.success) {
        toast.success(result.message);
        router.refresh();
      } else {
        toast.error(result.error);
      }
    } catch (error) {
      console.error("Error skipping legal review:", error);
      toast.error("법무검토 Skip 처리 중 오류가 발생했습니다.");
    } finally {
      setSyncLoading(prev => ({ ...prev, legalSkip: false }));
    }
  };

  // 등록요청 핸들러
  const handleRegistrationRequest = () => {
    const approvalReadyRows = selectedRows.filter(row => row.status === "approval_ready");
    
    if (approvalReadyRows.length === 0) {
      toast.error("조건충족 상태의 벤더를 선택해주세요.");
      return;
    }
    
    if (approvalReadyRows.length > 1) {
      toast.error("정규업체 등록 요청은 한 번에 하나씩만 가능합니다.");
      return;
    }

    setRegistrationRequestDialog({
      open: true,
      registration: approvalReadyRows[0],
    });
  };

  const handleRegistrationRequestSubmit = async (requestData: any) => {
    if (!registrationRequestDialog.registration) return;

    setSyncLoading(prev => ({ ...prev, registrationRequest: true }));
    try {
      const result = await submitRegistrationRequest(registrationRequestDialog.registration.id, requestData);
      if (result.success) {
        toast.success(result.message);
        setRegistrationRequestDialog({ open: false, registration: null });
        window.location.reload(); // 데이터 새로고침
      } else {
        toast.error(result.error);
      }
    } catch (error) {
      console.error("등록요청 오류:", error);
      toast.error("등록요청 중 오류가 발생했습니다.");
    } finally {
      setSyncLoading(prev => ({ ...prev, registrationRequest: false }));
    }
  };

  // CP검토 상태인 선택된 행들 개수
  const cpReviewCount = selectedRows.filter(row => row.status === "cp_review").length;
  
  // 조건충족 상태인 선택된 행들 개수
  const approvalReadyCount = selectedRows.filter(row => row.status === "approval_ready").length;

  return (
    <div className="flex items-center gap-2">
      {/* <Button
        variant="outline"
        size="sm"
        onClick={handleSyncDocuments}
        disabled={syncLoading.documents || selectedRows.length === 0}
      >
        <FileText className="mr-2 h-4 w-4" />
        {syncLoading.documents ? "동기화 중..." : "문서 동기화"}
      </Button>
      
      <Button
        variant="outline"
        size="sm"
        onClick={handleSyncAgreements}
        disabled={syncLoading.agreements || selectedRows.length === 0}
      >
        <RefreshCw className="mr-2 h-4 w-4" />
        {syncLoading.agreements ? "동기화 중..." : "계약 동기화"}
      </Button> */}

      <Button
        variant="outline"
        size="sm"
        onClick={handleSendMissingContractRequest}
        disabled={syncLoading.missingContract || selectedRows.length === 0}
      >
        <FileWarning className="mr-2 h-4 w-4" />
        {syncLoading.missingContract ? "발송 중..." : "누락계약요청"}
      </Button>

      <Button
        variant="outline"
        size="sm"
        onClick={handleSendAdditionalInfoRequest}
        disabled={syncLoading.additionalInfo || selectedRows.length === 0}
      >
        <Mail className="mr-2 h-4 w-4" />
        {syncLoading.additionalInfo ? "발송 중..." : "추가정보요청"}
      </Button>

      <Button
        variant="outline"
        size="sm"
        onClick={() => setSkipDialogs(prev => ({ ...prev, legalReview: true }))}
        disabled={syncLoading.legalSkip || cpReviewCount === 0}
      >
        <Scale className="mr-2 h-4 w-4" />
        {syncLoading.legalSkip ? "처리 중..." : "GTC Skip"}
      </Button>

      <Button
        variant="default"
        size="sm"
        onClick={handleRegistrationRequest}
        disabled={syncLoading.registrationRequest || approvalReadyCount === 0}
      >
        <FileText className="mr-2 h-4 w-4" />
        {syncLoading.registrationRequest ? "처리 중..." : "등록요청"}
      </Button>

      <SkipReasonDialog
        open={skipDialogs.legalReview}
        onOpenChange={(open) => setSkipDialogs(prev => ({ ...prev, legalReview: open }))}
        title="GTC Skip"
        description={`선택된 ${cpReviewCount}개 업체의 GTC를 Skip하고 CP완료 상태로 변경합니다. Skip 사유를 입력해주세요.`}
        onConfirm={handleLegalReviewSkip}
        loading={syncLoading.legalSkip}
      />

      <RegistrationRequestDialog
        open={registrationRequestDialog.open}
        onOpenChange={(open) => setRegistrationRequestDialog(prev => ({ ...prev, open }))}
        registration={registrationRequestDialog.registration}
        onSubmit={handleRegistrationRequestSubmit}
      />
    </div>
  )
}
