import { useEffect, useState, useCallback } from 'react'
import { api } from '../api/client'
import { Spinner } from '../components/Spinner'
import { Layout } from '../components/Layout'

interface UserOut {
  id: string
  first_name: string
  last_name: string
  email: string
  role: string
  company_id: string
}

interface AbsenceTypeOut {
  id: string
  company_id: string
  name: string
  color: string
  requires_approval: boolean
  deducts_vacation: boolean
  is_paid: boolean
  max_days_per_year: number | null
  is_active: boolean
}

interface AbsenceTypeCreate {
  name: string
  color: string
  requires_approval: boolean
  deducts_vacation: boolean
  is_paid: boolean
  max_days_per_year: number | null
}

interface AbsenceTypeUpdate {
  name?: string
  color?: string
  requires_approval?: boolean
  deducts_vacation?: boolean
  is_paid?: boolean
  max_days_per_year?: number | null
  is_active?: boolean
}

const ADMIN_ROLES = ['COMPANY_ADMIN', 'SUPER_ADMIN']

const DEFAULT_FORM: AbsenceTypeCreate = {
  name: '',
  color: '#3B82F6',
  requires_approval: true,
  deducts_vacation: false,
  is_paid: true,
  max_days_per_year: null,
}

export function AbsenceTypesPage() {
  const [user, setUser] = useState<UserOut | null>(null)
  const [types, setTypes] = useState<AbsenceTypeOut[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  // Modal state
  const [modalOpen, setModalOpen] = useState(false)
  const [editTarget, setEditTarget] = useState<AbsenceTypeOut | null>(null)
  const [form, setForm] = useState<AbsenceTypeCreate>({ ...DEFAULT_FORM })
  const [formError, setFormError] = useState<string | null>(null)
  const [saving, setSaving] = useState(false)

  const isAdmin = user !== null && ADMIN_ROLES.includes(user.role)

  const loadData = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const [me, list] = await Promise.all([
        api.get<UserOut>('/auth/me'),
        api.get<AbsenceTypeOut[]>('/absence-types/'),
      ])
      setUser(me)
      setTypes(list)
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Fehler beim Laden der Daten')
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    loadData()
  }, [loadData])

  // ── Modal helpers ───────────────────────────────────────────────────────────

  function openCreate() {
    setEditTarget(null)
    setForm({ ...DEFAULT_FORM })
    setFormError(null)
    setModalOpen(true)
  }

  function openEdit(type: AbsenceTypeOut) {
    setEditTarget(type)
    setForm({
      name: type.name,
      color: type.color,
      requires_approval: type.requires_approval,
      deducts_vacation: type.deducts_vacation,
      is_paid: type.is_paid,
      max_days_per_year: type.max_days_per_year,
    })
    setFormError(null)
    setModalOpen(true)
  }

  function closeModal() {
    setModalOpen(false)
    setEditTarget(null)
    setFormError(null)
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!form.name.trim()) {
      setFormError('Name ist erforderlich.')
      return
    }
    if (!/^#[0-9A-Fa-f]{6}$/.test(form.color)) {
      setFormError('Farbe muss im Format #RRGGBB angegeben werden.')
      return
    }
    setSaving(true)
    setFormError(null)
    try {
      if (editTarget) {
        const updated = await api.patch<AbsenceTypeOut>(
          `/absence-types/${editTarget.id}`,
          form as AbsenceTypeUpdate,
        )
        setTypes(prev => prev.map(t => (t.id === updated.id ? updated : t)))
      } else {
        const created = await api.post<AbsenceTypeOut>('/absence-types/', form)
        setTypes(prev => [...prev, created])
      }
      closeModal()
    } catch (e) {
      setFormError(e instanceof Error ? e.message : 'Speichern fehlgeschlagen')
    } finally {
      setSaving(false)
    }
  }

  async function toggleActive(type: AbsenceTypeOut) {
    try {
      const updated = await api.patch<AbsenceTypeOut>(
        `/absence-types/${type.id}`,
        { is_active: !type.is_active } satisfies AbsenceTypeUpdate,
      )
      setTypes(prev => prev.map(t => (t.id === updated.id ? updated : t)))
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Aktualisierung fehlgeschlagen')
    }
  }

  // ── Render ──────────────────────────────────────────────────────────────────

  if (loading) {
    return (
      <Layout userRole={user?.role ?? ''} userName={user ? `${user.first_name} ${user.last_name}` : ''}>
        <div className="flex items-center justify-center h-64">
          <Spinner />
        </div>
      </Layout>
    )
  }

  return (
    <Layout userRole={user?.role ?? ''} userName={user ? `${user.first_name} ${user.last_name}` : ''}>
      <div className="max-w-5xl mx-auto px-4 py-8">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">Abwesenheitstypen</h1>
            <p className="text-sm text-gray-500 mt-1">
              Verwalten Sie die Abwesenheitskategorien Ihres Unternehmens.
            </p>
          </div>
          {isAdmin && (
            <button
              onClick={openCreate}
              className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors"
            >
              <span className="text-lg leading-none">+</span>
              Abwesenheitstyp
            </button>
          )}
        </div>

        {/* Error banner */}
        {error && (
          <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
            {error}
          </div>
        )}

        {/* Table */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
          {types.length === 0 ? (
            <div className="py-16 text-center text-gray-400 text-sm">
              Keine Abwesenheitstypen vorhanden.
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="bg-gray-50 border-b border-gray-200 text-left">
                    <th className="px-4 py-3 font-semibold text-gray-600 w-8">Farbe</th>
                    <th className="px-4 py-3 font-semibold text-gray-600">Name</th>
                    <th className="px-4 py-3 font-semibold text-gray-600 text-center">
                      Genehmigung erforderlich
                    </th>
                    <th className="px-4 py-3 font-semibold text-gray-600 text-center">
                      Urlaubsabzug
                    </th>
                    <th className="px-4 py-3 font-semibold text-gray-600 text-center">
                      Bezahlt
                    </th>
                    <th className="px-4 py-3 font-semibold text-gray-600 text-center">
                      Max. Tage/Jahr
                    </th>
                    <th className="px-4 py-3 font-semibold text-gray-600 text-center">
                      Status
                    </th>
                    {isAdmin && (
                      <th className="px-4 py-3 font-semibold text-gray-600 text-right">
                        Aktionen
                      </th>
                    )}
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {types.map(type => (
                    <tr
                      key={type.id}
                      className={`hover:bg-gray-50 transition-colors ${
                        !type.is_active ? 'opacity-50' : ''
                      }`}
                    >
                      {/* Color dot */}
                      <td className="px-4 py-3">
                        <span
                          className="inline-block w-4 h-4 rounded-full border border-black/10"
                          style={{ backgroundColor: type.color }}
                        />
                      </td>

                      {/* Name */}
                      <td className="px-4 py-3 font-medium text-gray-900">{type.name}</td>

                      {/* Requires approval */}
                      <td className="px-4 py-3 text-center">
                        {type.requires_approval ? (
                          <span className="inline-block px-2 py-0.5 bg-blue-100 text-blue-700 rounded-full text-xs font-medium">
                            Ja
                          </span>
                        ) : (
                          <span className="inline-block px-2 py-0.5 bg-gray-100 text-gray-500 rounded-full text-xs font-medium">
                            Nein
                          </span>
                        )}
                      </td>

                      {/* Deducts vacation */}
                      <td className="px-4 py-3 text-center">
                        {type.deducts_vacation ? (
                          <span className="inline-block px-2 py-0.5 bg-orange-100 text-orange-700 rounded-full text-xs font-medium">
                            Ja
                          </span>
                        ) : (
                          <span className="inline-block px-2 py-0.5 bg-gray-100 text-gray-500 rounded-full text-xs font-medium">
                            Nein
                          </span>
                        )}
                      </td>

                      {/* Is paid */}
                      <td className="px-4 py-3 text-center">
                        {type.is_paid ? (
                          <span className="inline-block px-2 py-0.5 bg-green-100 text-green-700 rounded-full text-xs font-medium">
                            Ja
                          </span>
                        ) : (
                          <span className="inline-block px-2 py-0.5 bg-red-100 text-red-600 rounded-full text-xs font-medium">
                            Nein
                          </span>
                        )}
                      </td>

                      {/* Max days */}
                      <td className="px-4 py-3 text-center text-gray-700">
                        {type.max_days_per_year !== null ? type.max_days_per_year : '—'}
                      </td>

                      {/* Active toggle */}
                      <td className="px-4 py-3 text-center">
                        {isAdmin ? (
                          <button
                            onClick={() => toggleActive(type)}
                            className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium transition-colors ${
                              type.is_active
                                ? 'bg-green-100 text-green-700 hover:bg-green-200'
                                : 'bg-gray-100 text-gray-500 hover:bg-gray-200'
                            }`}
                          >
                            {type.is_active ? 'Aktiv' : 'Inaktiv'}
                          </button>
                        ) : (
                          <span
                            className={`inline-block px-2 py-0.5 rounded-full text-xs font-medium ${
                              type.is_active
                                ? 'bg-green-100 text-green-700'
                                : 'bg-gray-100 text-gray-500'
                            }`}
                          >
                            {type.is_active ? 'Aktiv' : 'Inaktiv'}
                          </span>
                        )}
                      </td>

                      {/* Edit action */}
                      {isAdmin && (
                        <td className="px-4 py-3 text-right">
                          <button
                            onClick={() => openEdit(type)}
                            className="text-blue-600 hover:text-blue-800 text-xs font-medium transition-colors"
                          >
                            Bearbeiten
                          </button>
                        </td>
                      )}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>

      {/* ── Create / Edit Modal ─────────────────────────────────────────────── */}
      {modalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4">
          <div className="bg-white rounded-2xl shadow-xl w-full max-w-md">
            {/* Modal header */}
            <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
              <h2 className="text-lg font-semibold text-gray-900">
                {editTarget ? 'Abwesenheitstyp bearbeiten' : 'Neuer Abwesenheitstyp'}
              </h2>
              <button
                onClick={closeModal}
                className="text-gray-400 hover:text-gray-600 transition-colors text-xl leading-none"
              >
                ×
              </button>
            </div>

            {/* Form */}
            <form onSubmit={handleSubmit} className="px-6 py-5 space-y-4">
              {formError && (
                <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
                  {formError}
                </div>
              )}

              {/* Name */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Name <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={form.name}
                  onChange={e => setForm(f => ({ ...f, name: e.target.value }))}
                  placeholder="z. B. Urlaub"
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  required
                />
              </div>

              {/* Color */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Farbe</label>
                <div className="flex items-center gap-3">
                  <input
                    type="color"
                    value={form.color}
                    onChange={e => setForm(f => ({ ...f, color: e.target.value }))}
                    className="h-9 w-14 cursor-pointer rounded border border-gray-300 p-0.5"
                  />
                  <input
                    type="text"
                    value={form.color}
                    onChange={e => setForm(f => ({ ...f, color: e.target.value }))}
                    placeholder="#3B82F6"
                    maxLength={7}
                    className="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
              </div>

              {/* Max days per year */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Max. Tage pro Jahr{' '}
                  <span className="text-gray-400 font-normal">(leer = unbegrenzt)</span>
                </label>
                <input
                  type="number"
                  min={1}
                  value={form.max_days_per_year ?? ''}
                  onChange={e =>
                    setForm(f => ({
                      ...f,
                      max_days_per_year: e.target.value === '' ? null : Number(e.target.value),
                    }))
                  }
                  placeholder="z. B. 30"
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              {/* Boolean flags */}
              <fieldset className="space-y-2">
                <legend className="text-sm font-medium text-gray-700 mb-1">Eigenschaften</legend>

                <label className="flex items-center gap-3 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={form.requires_approval}
                    onChange={e => setForm(f => ({ ...f, requires_approval: e.target.checked }))}
                    className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                  />
                  <span className="text-sm text-gray-700">Genehmigung erforderlich</span>
                </label>

                <label className="flex items-center gap-3 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={form.deducts_vacation}
                    onChange={e => setForm(f => ({ ...f, deducts_vacation: e.target.checked }))}
                    className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                  />
                  <span className="text-sm text-gray-700">Urlaubsabzug (zählt vom Urlaubskonto ab)</span>
                </label>

                <label className="flex items-center gap-3 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={form.is_paid}
                    onChange={e => setForm(f => ({ ...f, is_paid: e.target.checked }))}
                    className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                  />
                  <span className="text-sm text-gray-700">Bezahlt</span>
                </label>

                {/* is_active only available when editing */}
                {editTarget && (
                  <label className="flex items-center gap-3 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={(form as AbsenceTypeUpdate).is_active ?? editTarget.is_active}
                      onChange={e =>
                        setForm(f => ({ ...f, is_active: e.target.checked } as AbsenceTypeCreate))
                      }
                      className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                    />
                    <span className="text-sm text-gray-700">Aktiv</span>
                  </label>
                )}
              </fieldset>

              {/* Actions */}
              <div className="flex justify-end gap-3 pt-2">
                <button
                  type="button"
                  onClick={closeModal}
                  disabled={saving}
                  className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors disabled:opacity-50"
                >
                  Abbrechen
                </button>
                <button
                  type="submit"
                  disabled={saving}
                  className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50"
                >
                  {saving && <Spinner />}
                  {editTarget ? 'Speichern' : 'Erstellen'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </Layout>
  )
}
