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
  email: string
  department: string
  userRole: 'admin' | 'superuser' | 'user'
  createUser: boolean
}

export default function EmployeeForm() {
  const navigate = useNavigate()
  const { id } = useParams()
  const isEdit = !!id
  
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const { register, handleSubmit, formState: { errors }, reset } = useForm<EmployeeFormData>()

  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,
        email: employee.email,
        department: employee.department,
        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('')

      const payload = {
        firstName: data.firstName,
        lastName: data.lastName,
        email: data.email,
        department: data.department,
        // Optional fields - Backend will handle defaults
        userRole: data.createUser ? data.userRole : undefined,
        createUser: data.createUser
      }

      if (isEdit) {
        await api.put(`/employees/${id}`, payload)
      } else {
        await api.post('/employees', payload)
      }

      navigate('/employees')
    } catch (err: any) {
      setError(err.response?.data?.error?.message || 'Speichern fehlgeschlagen')
    } 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>
        )}

        <div className="card mb-6">
          <h2 className="text-title-card font-poppins font-semibold text-primary mb-6">
            Profilinformationen
          </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">
                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>
              <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>
        </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 text-secondary">
                  Benutzerkonto für diese Person erstellen
                </span>
              </label>
              <p className="text-small text-tertiary mt-1">
                Wenn aktiviert, wird automatisch ein Benutzerkonto mit der E-Mail-Adresse erstellt
              </p>
            </div>

            <div>
              <label className="block text-body font-medium text-secondary mb-2">
                Nutzerrolle
              </label>
              <div className="space-y-3">
                {(['admin', 'superuser', 'user'] as const).map((role) => (
                  <label key={role} className="flex items-start space-x-3 cursor-pointer group">
                    <input
                      {...register('userRole', { required: false })}
                      type="radio"
                      value={role}
                      className="w-5 h-5 mt-0.5 text-primary-blue focus:ring-primary-blue"
                    />
                    <div className="flex-1">
                      <div className="font-medium text-secondary capitalize">
                        {role === 'admin' ? 'Administrator' : 
                         role === 'superuser' ? 'Superuser' : 'Benutzer'}
                      </div>
                      <div className="text-small text-tertiary mt-1" title={getRoleDescription(role)}>
                        {getRoleDescription(role)}
                      </div>
                    </div>
                  </label>
                ))}
              </div>
            </div>
          </div>
        </div>

        <div className="flex justify-end space-x-3">
          <button
            type="button"
            onClick={() => navigate('/employees')}
            className="btn-secondary"
          >
            Abbrechen
          </button>
          <button
            type="submit"
            disabled={loading}
            className="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {loading ? 'Speichern...' : (isEdit ? 'Änderungen speichern' : 'Profil anlegen')}
          </button>
        </div>
      </form>
    </div>
  )
}
