"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { Plus } from "lucide-react"
import { toast } from "sonner"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { createContract } from "@/lib/general-contracts/service"
import { 
  GENERAL_CONTRACT_CATEGORIES, 
  GENERAL_CONTRACT_TYPES,
  GENERAL_EXECUTION_METHODS
} from "@/lib/general-contracts/types"
import { useSession } from "next-auth/react"
import { VendorSelectorDialogSingle } from "@/components/common/vendor/vendor-selector-dialog-single"
import { VendorSearchItem } from "@/components/common/vendor/vendor-service"

interface CreateContractForm {
  contractNumber: string
  name: string
  category: string
  type: string
  executionMethod: string
  startDate: string
  endDate: string
  validityEndDate: string
  notes: string
}

export function CreateGeneralContractDialog() {
  const router = useRouter()
  const { data: session } = useSession()
  const [open, setOpen] = React.useState(false)
  const [isLoading, setIsLoading] = React.useState(false)
  const [selectedVendor, setSelectedVendor] = React.useState<VendorSearchItem | null>(null)

  const [form, setForm] = React.useState<CreateContractForm>({
    contractNumber: '',
    name: '',
    category: '',
    type: '',
    executionMethod: '',
    startDate: '',
    endDate: '',
    validityEndDate: '',
    notes: '',
  })

  const handleSubmit = async () => {
    // 필수 필드 검증
    const validationErrors: string[] = []
    
    if (!form.name) validationErrors.push('계약명')
    if (!form.category) validationErrors.push('계약구분')
    if (!form.type) validationErrors.push('계약종류')
    if (!form.executionMethod) validationErrors.push('체결방식')
    if (!selectedVendor) validationErrors.push('협력업체')
    
    // AD, LO, OF 계약이 아닌 경우에만 계약기간 필수값 체크
    if (!['AD', 'LO', 'OF'].includes(form.type)) {
      if (!form.startDate) validationErrors.push('계약시작일')
      if (!form.endDate) validationErrors.push('계약종료일')
    }
    
    // LO 계약인 경우 계약체결유효기간 필수값 체크
    if (form.type === 'LO' && !form.validityEndDate) {
      validationErrors.push('유효기간')
    }
    
    if (validationErrors.length > 0) {
      toast.error(`다음 필수 항목을 입력해주세요: ${validationErrors.join(', ')}`)
      return
    }

    if (!form.validityEndDate) {
      setForm(prev => ({ ...prev, validityEndDate: form.endDate }))
    }

    try {
      setIsLoading(true)
      
      const contractData = {
        contractNumber: '',
        name: form.name,
        category: form.category,
        type: form.type,
        executionMethod: form.executionMethod,
        contractSourceType: 'manual',
        vendorId: selectedVendor!.id,
        startDate: form.startDate,
        endDate: form.endDate,
        validityEndDate: form.validityEndDate || form.endDate,
        status: 'Draft',
        registeredById: session?.user?.id || 1,
        lastUpdatedById: session?.user?.id || 1,
        notes: form.notes,
      }

      await createContract(contractData)
      
      toast.success("새 계약이 생성되었습니다.")
      setOpen(false)
      resetForm()
      
      // 상세 페이지로 이동
      router.refresh()
    } catch (error) {
      console.error('Error creating contract:', error)
      toast.error("계약 생성 중 오류가 발생했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  const resetForm = () => {
    setForm({
      contractNumber: '',
      name: '',
      category: '',
      type: '',
      executionMethod: '',
      startDate: '',
      endDate: '',
      validityEndDate: '',
      notes: '',
    })
    setSelectedVendor(null)
  }

  return (
    <Dialog open={open} onOpenChange={(newOpen) => {
      setOpen(newOpen)
      if (!newOpen) resetForm()
    }}>
      <DialogTrigger asChild>
        <Button size="sm">
          <Plus className="mr-2 h-4 w-4" />
          신규등록
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>새 계약 등록</DialogTitle>
          <DialogDescription>
            새로운 계약의 기본 정보를 입력하세요.
          </DialogDescription>
        </DialogHeader>
        
        <div className="grid gap-4 py-4">
          <div className="grid grid-cols-1 gap-4">
            <div className="grid gap-2">
              <Label htmlFor="name">계약명 *</Label>
              <Input
                id="name"
                value={form.name}
                onChange={(e) => setForm(prev => ({ ...prev, name: e.target.value }))}
                placeholder="계약명을 입력하세요"
              />
              {form.type === 'SC' && (
                <p className="text-sm text-blue-600 mt-1">
                  납품예정 품목 및 수량을 명기하세요. 납품 품목 또는 작업 내용은 구체적으로 작성하되, 수량(물량)이 정확하지 않을 경우, 상호협의하에 변경 가능하며, 수량(물량) 등은 개별계약(PO)시 명기하세요
                </p>
              )}
            </div>
          </div>

          <div className="grid grid-cols-3 gap-4">
            <div className="grid gap-2">
              <Label htmlFor="category">계약구분 *</Label>
              <Select value={form.category} onValueChange={(value) => setForm(prev => ({ ...prev, category: value }))}>
                <SelectTrigger>
                  <SelectValue placeholder="계약구분 선택" />
                </SelectTrigger>
                <SelectContent>
                  {GENERAL_CONTRACT_CATEGORIES.map((category) => {
                    const categoryLabels = {
                      'unit_price': '단가계약',
                      'general': '일반계약',
                      'sale': '매각계약'
                    }
                    return (
                    <SelectItem key={category} value={category}>
                      {category} - {categoryLabels[category as keyof typeof categoryLabels]}
                      </SelectItem>
                    )
                  })}
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="type">계약종류 *</Label>
              <Select value={form.type} onValueChange={(value) => setForm(prev => ({ ...prev, type: value }))}>
                <SelectTrigger>
                  <SelectValue placeholder="계약종류 선택" />
                </SelectTrigger>
                <SelectContent>
                  {GENERAL_CONTRACT_TYPES.map((type) => {
                    const typeLabels = {
                      'UP': '자재단가계약',
                      'LE': '임대차계약',
                      'IL': '개별운송계약',
                      'AL': '연간운송계약',
                      'OS': '외주용역계약',
                      'OW': '도급계약',
                      'LO': 'LOI',
                      'FA': 'FA',
                      'SC': '납품합의계약',
                      'OF': '클레임상계계약',
                      'AW': '사전작업합의',
                      'AD': '사전납품합의',
                      'SG': '임치(물품보관)계약',
                      'SR': '폐기물매각계약',
                      'SP': 'S-PEpC'
                    }
                    return (
                      <SelectItem key={type} value={type}>
                        {type} - {typeLabels[type as keyof typeof typeLabels]}
                      </SelectItem>
                    )
                  })}
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="executionMethod">체결방식 *</Label>
              <Select value={form.executionMethod} onValueChange={(value) => setForm(prev => ({ ...prev, executionMethod: value }))}>
                <SelectTrigger>
                  <SelectValue placeholder="체결방식 선택" />
                </SelectTrigger>
                <SelectContent>
                  {GENERAL_EXECUTION_METHODS.map((method) => (
                    <SelectItem key={method} value={method}>
                      {method}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="grid gap-2">
            <Label htmlFor="vendor">협력업체 *</Label>
            <VendorSelectorDialogSingle
              triggerLabel="협력업체 선택"
              selectedVendor={selectedVendor}
              onVendorSelect={setSelectedVendor}
              placeholder="협력업체를 검색하세요..."
              title="협력업체 선택"
              description="계약할 협력업체를 검색하고 선택해주세요."
              triggerVariant="outline"
              statusFilter="ACTIVE"
              showInitialData={true}
            />
          </div>

          <div className="grid grid-cols-3 gap-4">
            <div className="grid gap-2">
              <Label htmlFor="startDate">
                계약시작일
                {!['AD', 'LO', 'OF'].includes(form.type) && <span className="text-red-600 ml-1">*</span>}
              </Label>
              <Input
                id="startDate"
                type="date"
                value={form.startDate}
                onChange={(e) => setForm(prev => ({ ...prev, startDate: e.target.value }))}
                min="1900-01-01"
                max="2100-12-31"
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="endDate">
                계약종료일
                {!['AD', 'LO', 'OF'].includes(form.type) && <span className="text-red-600 ml-1">*</span>}
              </Label>
              <Input
                id="endDate"
                type="date"
                value={form.endDate}
                onChange={(e) => setForm(prev => ({ ...prev, endDate: e.target.value }))}
                min="1900-01-01"
                max="2100-12-31"
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="validityEndDate">유효기간종료일</Label>
              <Input
                id="validityEndDate"
                type="date"
                value={form.validityEndDate}
                onChange={(e) => setForm(prev => ({ ...prev, validityEndDate: e.target.value }))}
                min="1900-01-01"
                max="2100-12-31"
              />
            </div>
          </div>
          <div className="grid gap-2">
            <Label htmlFor="notes">비고</Label>
            <Textarea
              id="notes"
              value={form.notes}
              onChange={(e) => setForm(prev => ({ ...prev, notes: e.target.value }))}
              placeholder="비고사항을 입력하세요"
              rows={3}
            />
          </div>
        </div>

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={() => setOpen(false)}
          >
            취소
          </Button>
          <Button
            type="button"
            onClick={handleSubmit}
            disabled={isLoading}
          >
            {isLoading ? '생성 중...' : '생성'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
