import { useNavigate, useParams } from 'react-router-dom'
import { useForm } from 'react-hook-form'
import { useState, useEffect } from 'react'
import { api } from '../services/api'
import type { UserRole } from '@skillmate/shared'

interface EmployeeFormData {
  firstName: string
  lastName: string
  employeeNumber: string
  email: string
  phone: string
  position: string
  department: string
  office?: string
  mobile?: string
  availability: 'available' | 'busy' | 'away' | 'unavailable'
  userRole: 'admin' | 'superuser' | 'user'
  createUser: boolean
}

export default function EmployeeFormComplete() {
  const navigate = useNavigate()
  const { id } = useParams()
  const isEdit = !!id
  
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  const [createdUser, setCreatedUser] = useState<{password?: string}>({})

  const { register, handleSubmit, formState: { errors }, reset, watch } = useForm<EmployeeFormData>({
    defaultValues: {
      availability: 'available',
      userRole: 'user',
      createUser: false
    }
  })

  const watchCreateUser = watch('createUser')

  useEffect(() => {
    if (isEdit) {
      fetchEmployee()
    }
  }, [id])

  const fetchEmployee = async () => {
    try {
      const response = await api.get(`/employees/${id}`)
      const employee = response.data.data
      
      reset({
        firstName: employee.firstName,
        lastName: employee.lastName,
        employeeNumber: employee.employeeNumber,
        email: employee.email,
        phone: employee.phone,
        position: employee.position,
        department: employee.department,
        office: employee.office,
        mobile: employee.mobile,
        availability: employee.availability,
        userRole: 'user',
        createUser: false
      })
    } catch (error) {
      console.error('Failed to fetch employee:', error)
      setError('Profil konnte nicht geladen werden')
    }
  }

  const onSubmit = async (data: EmployeeFormData) => {
    try {
      setLoading(true)
      setError('')
      setSuccess('')

      const payload = {
        firstName: data.firstName,
        lastName: data.lastName,
        employeeNumber: data.employeeNumber || `EMP${Date.now()}`,
        email: data.email,
        phone: data.phone,
        position: data.position,
        department: data.department,
        office: data.office || null,
        mobile: data.mobile || null,
        availability: data.availability,
        skills: [],
        languages: [],
        specializations: [],
        userRole: data.createUser ? data.userRole : undefined,
        createUser: data.createUser
      }

      let response
      if (isEdit) {
        response = await api.put(`/employees/${id}`, payload)
        setSuccess('Profil erfolgreich aktualisiert!')
      } else {
        response = await api.post('/employees', payload)
        
        if (response.data.data.temporaryPassword) {
          setCreatedUser({ password: response.data.data.temporaryPassword })
          setSuccess(`Profil erfolgreich erstellt! Temporäres Passwort: ${response.data.data.temporaryPassword}`)
        } else {
          setSuccess('Profil erfolgreich erstellt!')
        }
      }

      setTimeout(() => {
        navigate('/employees')
      }, 3000)
    } catch (err: any) {
      console.error('Error:', err.response?.data)
      const errorMessage = err.response?.data?.error?.message || 'Speichern fehlgeschlagen'
      const errorDetails = err.response?.data?.error?.details
      
      if (errorDetails && Array.isArray(errorDetails)) {
        const detailMessages = errorDetails.map((d: any) => d.msg || d.message).join(', ')
        setError(`${errorMessage}: ${detailMessages}`)
      } else {
        setError(errorMessage)
      }
    } finally {
      setLoading(false)
    }
  }

  const getRoleDescription = (role: UserRole): string => {
    const descriptions = {
      admin: 'Vollzugriff auf alle Funktionen inklusive Admin Panel und Benutzerverwaltung',
      superuser: 'Kann Mitarbeitende anlegen und verwalten, aber kein Zugriff auf Admin Panel',
      user: 'Kann nur das eigene Profil bearbeiten und Mitarbeitende durchsuchen'
    }
    return descriptions[role]
  }

  return (
    <div>
      <div className="mb-8">
        <button
          onClick={() => navigate('/employees')}
          className="text-primary-blue hover:text-primary-blue-hover mb-4"
        >
          ← Zurück zur Übersicht
        </button>
        <h1 className="text-title-lg font-poppins font-bold text-primary">
          {isEdit ? 'Mitarbeitendenprofil bearbeiten' : 'Neues Mitarbeitendenprofil'}
        </h1>
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="max-w-4xl">
        {error && (
          <div className="bg-error-bg text-error px-4 py-3 rounded-input text-sm mb-6">
            {error}
          </div>
        )}

        {success && (
          <div className="bg-green-50 text-green-800 px-4 py-3 rounded-input text-sm mb-6">
            {success}
            {createdUser.password && (
              <div className="mt-2 p-2 bg-white rounded border border-green-300">
                <strong>Bitte notieren Sie das temporäre Passwort:</strong>
                <br />
                <code className="text-lg">{createdUser.password}</code>
              </div>
            )}
          </div>
        )}

        <div className="card mb-6">
          <h2 className="text-title-card font-poppins font-semibold text-primary mb-6">
            Persönliche Daten
          </h2>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-body font-medium text-secondary mb-2">
                Vorname *
              </label>
              <input
                {...register('firstName', { required: 'Vorname ist erforderlich' })}
                className="input-field w-full"
                placeholder="Max"
              />
              {errors.firstName && (
                <p className="text-error text-sm mt-1">{errors.firstName.message}</p>
              )}
            </div>

            <div>
              <label className="block text-body font-medium text-secondary mb-2">
                Nachname *
              </label>
              <input
                {...register('lastName', { required: 'Nachname ist erforderlich' })}
                className="input-field w-full"
                placeholder="Mustermann"
              />
              {errors.lastName && (
                <p className="text-error text-sm mt-1">{errors.lastName.message}</p>
              )}
            </div>

            <div>
              <label className="block text-body font-medium text-secondary mb-2">
                Personalnummer *
              </label>
              <input
                {...register('employeeNumber', { required: 'Personalnummer ist erforderlich' })}
                className="input-field w-full"
                placeholder="EMP001"
              />
              {errors.employeeNumber && (
                <p className="text-error text-sm mt-1">{errors.employeeNumber.message}</p>
              )}
            </div>

            <div>
              <label className="block text-body font-medium text-secondary mb-2">
                E-Mail *
              </label>
              <input
                {...register('email', { 
                  required: 'E-Mail ist erforderlich',
                  pattern: {
                    value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                    message: 'Ungültige E-Mail-Adresse'
                  }
                })}
                type="email"
                className="input-field w-full"
                placeholder="max.mustermann@firma.de"
              />
              {errors.email && (
                <p className="text-error text-sm mt-1">{errors.email.message}</p>
              )}
            </div>
          </div>
        </div>

        <div className="card mb-6">
          <h2 className="text-title-card font-poppins font-semibold text-primary mb-6">
            Kontaktdaten & Position
          </h2>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-body font-medium text-secondary mb-2">
                Telefon *
              </label>
              <input
                {...register('phone', { required: 'Telefonnummer ist erforderlich' })}
                className="input-field w-full"
                placeholder="+49 123 456789"
              />
              {errors.phone && (
                <p className="text-error text-sm mt-1">{errors.phone.message}</p>
              )}
            </div>

            <div>
              <label className="block text-body font-medium text-secondary mb-2">
                Mobil (optional)
              </label>
              <input
                {...register('mobile')}
                className="input-field w-full"
                placeholder="+49 170 123456"
              />
            </div>

            <div>
              <label className="block text-body font-medium text-secondary mb-2">
                Position *
              </label>
              <input
                {...register('position', { required: 'Position ist erforderlich' })}
                className="input-field w-full"
                placeholder="Software Developer"
              />
              {errors.position && (
                <p className="text-error text-sm mt-1">{errors.position.message}</p>
              )}
            </div>

            <div>
              <label className="block text-body font-medium text-secondary mb-2">
                Abteilung *
              </label>
              <input
                {...register('department', { required: 'Abteilung ist erforderlich' })}
                className="input-field w-full"
                placeholder="IT, Personal, Buchhaltung, etc."
              />
              {errors.department && (
                <p className="text-error text-sm mt-1">{errors.department.message}</p>
              )}
            </div>

            <div>
              <label className="block text-body font-medium text-secondary mb-2">
                Büro (optional)
              </label>
              <input
                {...register('office')}
                className="input-field w-full"
                placeholder="Gebäude A, Raum 123"
              />
            </div>

            <div>
              <label className="block text-body font-medium text-secondary mb-2">
                Verfügbarkeit *
              </label>
              <select
                {...register('availability', { required: 'Verfügbarkeit ist erforderlich' })}
                className="input-field w-full"
              >
                <option value="available">Verfügbar</option>
                <option value="busy">Beschäftigt</option>
                <option value="away">Abwesend</option>
                <option value="unavailable">Nicht verfügbar</option>
              </select>
              {errors.availability && (
                <p className="text-error text-sm mt-1">{errors.availability.message}</p>
              )}
            </div>
          </div>
        </div>

        <div className="card mb-6">
          <h2 className="text-title-card font-poppins font-semibold text-primary mb-6">
            Benutzerkonto erstellen (optional)
          </h2>

          <div className="space-y-4">
            <div>
              <label className="flex items-center space-x-2 cursor-pointer">
                <input
                  {...register('createUser')}
                  type="checkbox"
                  className="w-5 h-5 rounded border-border-input text-primary-blue focus:ring-primary-blue"
                />
                <span className="text-body font-medium text-secondary">
                  Benutzerkonto für diese Person erstellen
                </span>
              </label>
              <p className="text-sm text-secondary-light mt-1 ml-7">
                Ein temporäres Passwort wird generiert und muss beim ersten Login geändert werden.
              </p>
            </div>

            {watchCreateUser && (
              <div>
                <label className="block text-body font-medium text-secondary mb-2">
                  Benutzerrolle
                </label>
                <select
                  {...register('userRole')}
                  className="input-field w-full"
                >
                  <option value="user">Benutzer</option>
                  <option value="superuser">Poweruser</option>
                  <option value="admin">Administrator</option>
                </select>
                <p className="text-sm text-secondary-light mt-1">
                  {getRoleDescription(watch('userRole'))}
                </p>
              </div>
            )}
          </div>
        </div>

        <div className="flex justify-end space-x-4">
          <button
            type="button"
            onClick={() => navigate('/employees')}
            className="btn-secondary"
            disabled={loading}
          >
            Abbrechen
          </button>
          <button
            type="submit"
            className="btn-primary"
            disabled={loading}
          >
            {loading ? 'Speichert...' : (isEdit ? 'Aktualisieren' : 'Erstellen')}
          </button>
        </div>
      </form>
    </div>
  )
}
