'use client'

import * as React from 'react'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { ScrollArea } from '@/components/ui/scroll-area'
import {
  Calendar,
  Users,
  Clock,
  CheckCircle,
  XCircle,
  Download,
} from 'lucide-react'

import { formatDate } from '@/lib/utils'
import { updatePartnerAttendance, getSpecificationMeetingForPartners } from '../detail/service'
import { useToast } from '@/hooks/use-toast'
import { useTransition } from 'react'
import { useRouter } from 'next/navigation'

interface PartnersSpecificationMeetingDialogProps {
  biddingDetail: {
    id: number
    biddingNumber: string
    title: string
    preQuoteDate: string | null
    biddingRegistrationDate: string | null
    evaluationDate: string | null
    hasSpecificationMeeting?: boolean // 사양설명회 여부 추가
  } | null
  biddingCompanyId: number
  isAttending: boolean | null
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function PartnersSpecificationMeetingDialog({
  biddingDetail,
  biddingCompanyId,
  isAttending,
  open,
  onOpenChange,
}: PartnersSpecificationMeetingDialogProps) {
  const { toast } = useToast()
  const [isPending, startTransition] = useTransition()
  const [isLoading, setIsLoading] = React.useState(false)
  const [meetingData, setMeetingData] = React.useState<any>(null)
  const router = useRouter()
  // 폼 상태
  const [attendance, setAttendance] = React.useState<string>('')
  const [attendeeCount, setAttendeeCount] = React.useState<string>('')
  const [representativeName, setRepresentativeName] = React.useState<string>('')
  const [representativePhone, setRepresentativePhone] = React.useState<string>('')

  // 사양설명회 정보 가져오기
  React.useEffect(() => {
    if (open && biddingDetail) {
      fetchMeetingData()
    }
  }, [open, biddingDetail])

  const fetchMeetingData = async () => {
    if (!biddingDetail) return
    
    setIsLoading(true)
    try {
      const result = await getSpecificationMeetingForPartners(biddingDetail.id)
      if (result.success) {
        setMeetingData(result.data)
      } else {
        toast({
          title: '오류',
          description: result.error,
          variant: 'destructive',
        })
      }
    } catch (error) {
      console.error('사양설명회 정보를 불러오는데 실패했습니다.', error)
      toast({
        title: '오류',
        description: '사양설명회 정보를 불러오는데 실패했습니다.',
        variant: 'destructive',
      })
    } finally {
      setIsLoading(false)
    }
  }

  // 다이얼로그 열릴 때 기존 값으로 초기화
  React.useEffect(() => {
    if (open) {
      if (isAttending === true) {
        setAttendance('attending')
      } else if (isAttending === false) {
        setAttendance('not_attending')
      } else {
        setAttendance('')
      }
      setAttendeeCount('')
      setRepresentativeName('')
      setRepresentativePhone('')
    }
  }, [open, isAttending])

  const handleSubmit = () => {
    if (!attendance) {
      toast({
        title: '선택 필요',
        description: '참석 여부를 선택해주세요.',
        variant: 'destructive',
      })
      return
    }

    // 참석하는 경우 필수 정보 체크
    if (attendance === 'attending') {
      if (!attendeeCount || !representativeName || !representativePhone) {
        toast({
          title: '필수 정보 누락',
          description: '참석인원수, 참석자 대표 이름, 연락처를 모두 입력해주세요.',
          variant: 'destructive',
        })
        return
      }

      const countNum = parseInt(attendeeCount)
      if (isNaN(countNum) || countNum < 1) {
        toast({
          title: '잘못된 입력',
          description: '참석인원수는 1 이상의 숫자를 입력해주세요.',
          variant: 'destructive',
        })
        return
      }
    }

    startTransition(async () => {
      const attendanceData = {
        isAttending: attendance === 'attending',
        attendeeCount: attendance === 'attending' ? parseInt(attendeeCount) : undefined,
        representativeName: attendance === 'attending' ? representativeName : undefined,
        representativePhone: attendance === 'attending' ? representativePhone : undefined,
      }

      const result = await updatePartnerAttendance(
        biddingCompanyId,
        attendanceData
      )

      if (result.success) {
        toast({
          title: '성공',
          description: result.message,
        })
        
        // 참석하는 경우 이메일 발송 알림
        if (attendance === 'attending' && result.data) {
          toast({
            title: '참석 알림 발송',
            description: '사양설명회 담당자에게 참석 알림이 발송되었습니다.',
          })
        }
        
        router.refresh()
        onOpenChange(false)
      } else {
        toast({
          title: '오류',
          description: result.error,
          variant: 'destructive',
        })
      }
    })
  }

  const handleFileDownload = async (filePath: string, fileName: string) => {
    try {
      const { downloadFile } = await import('@/lib/file-download')
      await downloadFile(filePath, fileName)
    } catch (error) {
      console.error('파일 다운로드 실패:', error)
      toast({
        title: '다운로드 실패',
        description: '파일 다운로드 중 오류가 발생했습니다.',
        variant: 'destructive',
      })
    }
  }

  if (!biddingDetail) return null

  // 사양설명회가 없는 경우
  if (biddingDetail.hasSpecificationMeeting === false) {
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Users className="w-5 h-5" />
              사양설명회 정보
            </DialogTitle>
          </DialogHeader>
          
          <div className="py-6 text-center">
            <XCircle className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
            <h3 className="text-lg font-medium mb-2">사양설명회 없음</h3>
            <p className="text-muted-foreground">
              해당 입찰 건은 사양설명회가 없습니다.
            </p>
          </div>

          <DialogFooter>
            <Button onClick={() => onOpenChange(false)}>
              확인
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    )
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Users className="w-5 h-5" />
            사양설명회
          </DialogTitle>
          <DialogDescription>
            {biddingDetail.title}의 사양설명회 정보 및 참석 여부를 확인해주세요.
          </DialogDescription>
        </DialogHeader>

        <ScrollArea className="max-h-[75vh]">
          {isLoading ? (
            <div className="flex items-center justify-center py-6">
              <div className="text-center">
                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary mx-auto mb-2"></div>
                <p className="text-sm text-muted-foreground">로딩 중...</p>
              </div>
            </div>
          ) : (
            <div className="space-y-6">
              {/* 사양설명회 기본 정보 */}
              {meetingData && (
                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-base flex items-center gap-2">
                      <Calendar className="w-4 h-4" />
                      설명회 정보
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="pt-0">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div>
                        <div className="text-sm space-y-2">
                          <div>
                            <span className="font-medium">설명회 일정:</span> 
                            <span className="ml-2">
                              {meetingData.meetingDate ? formatDate(meetingData.meetingDate, 'KR') : '미정'}
                            </span>
                          </div>
                          <div>
                            <span className="font-medium">설명회 담당자:</span>
                            <div className="ml-2 text-muted-foreground">
                              {meetingData.contactPerson && (
                                <div>{meetingData.contactPerson}</div>
                              )}
                              {meetingData.contactEmail && (
                                <div>{meetingData.contactEmail}</div>
                              )}
                              {meetingData.contactPhone && (
                                <div>{meetingData.contactPhone}</div>
                              )}
                            </div>
                          </div>
                        </div>
                      </div>
                      
                      <div>
                        <div className="text-sm">
                          <span className="font-medium">설명회 자료:</span>
                          <div className="mt-2 space-y-1">
                            {meetingData.documents && meetingData.documents.length > 0 ? (
                              meetingData.documents.map((doc: any) => (
                                <Button
                                  key={doc.id}
                                  variant="outline"
                                  size="sm"
                                  onClick={() => handleFileDownload(doc.filePath, doc.originalFileName)}
                                  className="flex items-center gap-2 h-8 text-xs"
                                >
                                  <Download className="w-3 h-3" />
                                  {doc.originalFileName}
                                </Button>
                              ))
                            ) : (
                              <span className="text-muted-foreground">첨부파일 없음</span>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* 참석 여부 입력 폼 */}
              <Card>
                <CardHeader className="pb-3">
                  <CardTitle className="text-base">참석 여부</CardTitle>
                </CardHeader>
                <CardContent className="pt-0 space-y-4">
                  <RadioGroup
                    value={attendance}
                    onValueChange={setAttendance}
                    className="space-y-3"
                  >
                    <div className="flex items-start space-x-3 p-3 border rounded-lg hover:bg-muted/50 transition-colors">
                      <RadioGroupItem value="attending" id="attending" className="mt-1" />
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-3">
                          <CheckCircle className="w-5 h-5 text-green-600" />
                          <Label htmlFor="attending" className="font-medium cursor-pointer">
                            Y (참석)
                          </Label>
                        </div>
                        
                        {attendance === 'attending' && (
                          <div className="space-y-3 mt-3 pl-2">
                            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                              <div>
                                <Label htmlFor="attendeeCount" className="text-xs">참석인원수</Label>
                                <Input
                                  id="attendeeCount"
                                  type="number"
                                  min="1"
                                  value={attendeeCount}
                                  onChange={(e) => setAttendeeCount(e.target.value)}
                                  placeholder="명"
                                  className="h-8 text-sm"
                                />
                              </div>
                              <div>
                                <Label htmlFor="representativeName" className="text-xs">참석자 대표(이름)</Label>
                                <Input
                                  id="representativeName"
                                  value={representativeName}
                                  onChange={(e) => setRepresentativeName(e.target.value)}
                                  placeholder="홍길동 과장"
                                  className="h-8 text-sm"
                                />
                              </div>
                              <div>
                                <Label htmlFor="representativePhone" className="text-xs">참석자 대표(연락처)</Label>
                                <Input
                                  id="representativePhone"
                                  value={representativePhone}
                                  onChange={(e) => setRepresentativePhone(e.target.value)}
                                  placeholder="010-0000-0000"
                                  className="h-8 text-sm"
                                />
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                    
                    <div className="flex items-center space-x-3 p-3 border rounded-lg hover:bg-muted/50 transition-colors">
                      <RadioGroupItem value="not_attending" id="not_attending" />
                      <div className="flex items-center gap-2 flex-1">
                        <XCircle className="w-5 h-5 text-red-600" />
                        <Label htmlFor="not_attending" className="font-medium cursor-pointer">
                          N (불참)
                        </Label>
                      </div>
                    </div>
                  </RadioGroup>
                </CardContent>
              </Card>

              {/* 현재 상태 표시 */}
              {isAttending !== null && (
                <Card>
                  <CardContent className="pt-6">
                    <div className="flex items-center gap-2 text-blue-800">
                      <Clock className="w-4 h-4" />
                      <span className="text-sm">
                        현재 상태: {isAttending ? '참석' : '불참'} ({formatDate(new Date().toISOString(), 'KR')} 기준)
                      </span>
                    </div>
                  </CardContent>
                </Card>
              )}
            </div>
          )}
        </ScrollArea>

        <DialogFooter className="flex gap-2">
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isPending}
          >
            취소
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={isPending || !attendance || isLoading}
            className="min-w-[100px]"
          >
            {isPending ? '저장 중...' : '확인'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
