'use client'

import * as React from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Checkbox } from '@/components/ui/checkbox'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { updateBiddingCompany } from '../service'
import { BiddingCompany } from './bidding-pre-quote-vendor-columns'
import { useToast } from '@/hooks/use-toast'
import { useTransition } from 'react'

interface BiddingPreQuoteVendorEditDialogProps {
  company: BiddingCompany | null
  open: boolean
  onOpenChange: (open: boolean) => void
  onSuccess: () => void
}

export function BiddingPreQuoteVendorEditDialog({
  company,
  open,
  onOpenChange,
  onSuccess
}: BiddingPreQuoteVendorEditDialogProps) {
  const { toast } = useToast()
  const [isPending, startTransition] = useTransition()

  // 폼 상태
  const [formData, setFormData] = React.useState({
    contactPerson: '',
    contactEmail: '',
    contactPhone: '',
    preQuoteAmount: 0,
    notes: '',
    invitationStatus: 'pending' as 'pending' | 'accepted' | 'declined',
    isPreQuoteSelected: false,
    isAttendingMeeting: false,
  })

  // company가 변경되면 폼 데이터 업데이트
  React.useEffect(() => {
    if (company) {
      setFormData({
        contactPerson: company.contactPerson || '',
        contactEmail: company.contactEmail || '',
        contactPhone: company.contactPhone || '',
        preQuoteAmount: company.preQuoteAmount ? Number(company.preQuoteAmount) : 0,
        notes: company.notes || '',
        invitationStatus: company.invitationStatus,
        isPreQuoteSelected: company.isPreQuoteSelected,
        isAttendingMeeting: company.isAttendingMeeting || false,
      })
    }
  }, [company])

  const handleEdit = () => {
    if (!company) return

    startTransition(async () => {
      const response = await updateBiddingCompany(company.id, formData)

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

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle>사전견적 업체 수정</DialogTitle>
          <DialogDescription>
            {company?.companyName} 업체의 사전견적 정보를 수정해주세요.
          </DialogDescription>
        </DialogHeader>
        <div className="grid gap-4 py-4">
          <div className="grid grid-cols-3 gap-4">
            <div className="space-y-2">
              <Label htmlFor="edit-contactPerson">담당자</Label>
              <Input
                id="edit-contactPerson"
                value={formData.contactPerson}
                onChange={(e) => setFormData({ ...formData, contactPerson: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="edit-contactEmail">이메일</Label>
              <Input
                id="edit-contactEmail"
                type="email"
                value={formData.contactEmail}
                onChange={(e) => setFormData({ ...formData, contactEmail: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="edit-contactPhone">연락처</Label>
              <Input
                id="edit-contactPhone"
                value={formData.contactPhone}
                onChange={(e) => setFormData({ ...formData, contactPhone: e.target.value })}
              />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="edit-preQuoteAmount">사전견적금액</Label>
              <Input
                id="edit-preQuoteAmount"
                type="number"
                value={formData.preQuoteAmount}
                onChange={(e) => setFormData({ ...formData, preQuoteAmount: Number(e.target.value) })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="edit-invitationStatus">초대 상태</Label>
              <Select value={formData.invitationStatus} onValueChange={(value: any) => setFormData({ ...formData, invitationStatus: value })}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="pending">대기중</SelectItem>
                  <SelectItem value="accepted">수락</SelectItem>
                  <SelectItem value="declined">거절</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="flex items-center space-x-2">
              <Checkbox
                id="edit-isPreQuoteSelected"
                checked={formData.isPreQuoteSelected}
                onCheckedChange={(checked) => 
                  setFormData({ ...formData, isPreQuoteSelected: !!checked })
                }
              />
              <Label htmlFor="edit-isPreQuoteSelected">본입찰 선정</Label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="edit-isAttendingMeeting"
                checked={formData.isAttendingMeeting}
                onCheckedChange={(checked) => 
                  setFormData({ ...formData, isAttendingMeeting: !!checked })
                }
              />
              <Label htmlFor="edit-isAttendingMeeting">사양설명회 참석</Label>
            </div>
          </div>
          <div className="space-y-2">
            <Label htmlFor="edit-notes">특이사항</Label>
            <Textarea
              id="edit-notes"
              value={formData.notes}
              onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
              placeholder="특이사항을 입력해주세요..."
            />
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            취소
          </Button>
          <Button onClick={handleEdit} disabled={isPending}>
            수정
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
