'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import {
  DSRType,
  DSRSource,
  DSRPriority,
  DSRCreateRequest
} from '@/lib/sdk/dsr/types'
import { createSDKDSR } from '@/lib/sdk/dsr/api'

export interface FormData {
  type: DSRType | ''
  requesterName: string
  requesterEmail: string
  requesterPhone: string
  requesterAddress: string
  source: DSRSource | ''
  sourceDetails: string
  requestText: string
  priority: DSRPriority
  customerId: string
}

export function useNewDSRForm() {
  const router = useRouter()
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [errors, setErrors] = useState<Record<string, string>>({})

  const [formData, setFormData] = useState<FormData>({
    type: '',
    requesterName: '',
    requesterEmail: '',
    requesterPhone: '',
    requesterAddress: '',
    source: '',
    sourceDetails: '',
    requestText: '',
    priority: 'normal',
    customerId: ''
  })

  const updateField = <K extends keyof FormData>(field: K, value: FormData[K]) => {
    setFormData(prev => ({ ...prev, [field]: value }))
    if (errors[field]) {
      setErrors(prev => {
        const newErrors = { ...prev }
        delete newErrors[field]
        return newErrors
      })
    }
  }

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {}

    if (!formData.type) {
      newErrors.type = 'Bitte waehlen Sie den Anfragetyp'
    }
    if (!formData.requesterName.trim()) {
      newErrors.requesterName = 'Name ist erforderlich'
    }
    if (!formData.requesterEmail.trim()) {
      newErrors.requesterEmail = 'E-Mail ist erforderlich'
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.requesterEmail)) {
      newErrors.requesterEmail = 'Bitte geben Sie eine gueltige E-Mail-Adresse ein'
    }
    if (!formData.source) {
      newErrors.source = 'Bitte waehlen Sie die Quelle der Anfrage'
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!validate()) return

    setIsSubmitting(true)
    try {
      const request: DSRCreateRequest = {
        type: formData.type as DSRType,
        requester: {
          name: formData.requesterName,
          email: formData.requesterEmail,
          phone: formData.requesterPhone || undefined,
          address: formData.requesterAddress || undefined,
          customerId: formData.customerId || undefined
        },
        source: formData.source as DSRSource,
        sourceDetails: formData.sourceDetails || undefined,
        requestText: formData.requestText || undefined,
        priority: formData.priority
      }

      await createSDKDSR(request)

      router.push('/sdk/dsr')
    } catch (error) {
      console.error('Failed to create DSR:', error)
      setErrors({ submit: 'Fehler beim Erstellen der Anfrage. Bitte versuchen Sie es erneut.' })
    } finally {
      setIsSubmitting(false)
    }
  }

  return { formData, errors, isSubmitting, updateField, handleSubmit }
}
