import { useEffect, useState } 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
}

interface ProjectOut {
  id: string
  name: string
  description: string | null
  color: string
  budget_hours: number | null
  is_active: boolean
  created_at: string
  updated_at: string
}

interface ProjectTimeReport {
  project_id: string
  project_name: string
  project_color: string
  total_hours: number
  entry_count: number
  budget_hours: number | null
  budget_used_pct: number | null
}

const COLORS = [
  '#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6',
  '#EC4899', '#06B6D4', '#84CC16', '#F97316', '#6B7280',
]

const MANAGER_ROLES = ['COMPANY_ADMIN', 'SUPER_ADMIN', 'HR', 'MANAGER']

const EMPTY_FORM = { name: '', description: '', color: '#3B82F6', budget_hours: '' }

function BudgetBar({ used, budget }: { used: number; budget: number }) {
  const pct = Math.min(100, Math.round((used / budget) * 100))
  const color = pct >= 100 ? 'bg-red-500' : pct >= 80 ? 'bg-amber-400' : 'bg-green-500'
  return (
    <div className='mt-1'>
      <div className='flex justify-between text-xs text-gray-500 mb-0.5'>
        <span>{used}h / {budget}h</span>
        <span className={pct >= 100 ? 'text-red-600 font-semibold' : ''}>{pct}%</span>
      </div>
      <div className='h-1.5 bg-gray-100 rounded-full overflow-hidden'>
        <div className={`h-full rounded-full ${color} transition-all`} style={{ width: `${pct}%` }} />
      </div>
    </div>
  )
}

export function ProjectsPage() {
  const [user, setUser] = useState<UserOut | null>(null)
  const [projects, setProjects] = useState<ProjectOut[]>([])
  const [summary, setSummary] = useState<ProjectTimeReport[]>([])
  const [loading, setLoading] = useState(true)
  const [showInactive, setShowInactive] = useState(false)

  const [modal, setModal] = useState<'create' | 'edit' | null>(null)
  const [editProject, setEditProject] = useState<ProjectOut | null>(null)
  const [form, setForm] = useState(EMPTY_FORM)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  const isManager = user ? MANAGER_ROLES.includes(user.role) : false

  const load = async () => {
    try {
      const [me, list] = await Promise.all([
        api.get<UserOut>('/auth/me'),
        api.get<{ total: number; items: ProjectOut[] }>(`/projects?include_inactive=${showInactive}`),
      ])
      setUser(me)
      setProjects(list.items)

      if (MANAGER_ROLES.includes(me.role)) {
        const s = await api.get<ProjectTimeReport[]>('/projects/report/summary').catch(() => [])
        setSummary(s)
      }
    } catch { /* ignore */ }
    finally { setLoading(false) }
  }

  useEffect(() => { load() }, [showInactive])

  const openCreate = () => {
    setEditProject(null)
    setForm(EMPTY_FORM)
    setError('')
    setModal('create')
  }

  const openEdit = (p: ProjectOut) => {
    setEditProject(p)
    setForm({ name: p.name, description: p.description ?? '', color: p.color, budget_hours: p.budget_hours?.toString() ?? '' })
    setError('')
    setModal('edit')
  }

  const save = async () => {
    setSaving(true); setError('')
    try {
      const payload = {
        name: form.name.trim(),
        description: form.description.trim() || null,
        color: form.color,
        budget_hours: form.budget_hours ? parseFloat(form.budget_hours) : null,
      }
      if (modal === 'create') {
        await api.post('/projects', payload)
      } else if (editProject) {
        await api.patch(`/projects/${editProject.id}`, payload)
      }
      setModal(null)
      await load()
    } catch (e: unknown) { setError(e instanceof Error ? e.message : 'Fehler') }
    finally { setSaving(false) }
  }

  const deactivate = async (p: ProjectOut) => {
    if (!confirm(`Projekt "${p.name}" deaktivieren?`)) return
    await api.patch(`/projects/${p.id}`, { is_active: false })
    await load()
  }

  const reactivate = async (p: ProjectOut) => {
    await api.patch(`/projects/${p.id}`, { is_active: true })
    await load()
  }

  const getSummary = (id: string) => summary.find(s => s.project_id === id)

  const inp = 'w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500'

  if (loading) return <Layout userRole='' userName=''><div className='flex justify-center py-20'><Spinner /></div></Layout>
  if (!user) return null

  return (
    <Layout userRole={user.role} userName={`${user.first_name} ${user.last_name}`}>
      <div className='max-w-4xl space-y-6'>

        {/* Header */}
        <div className='flex items-center justify-between'>
          <div>
            <h1 className='text-2xl font-bold text-gray-900'>Projekte</h1>
            <p className='text-sm text-gray-500 mt-1'>Zeiterfassung nach Projekten aufschlüsseln</p>
          </div>
          <div className='flex items-center gap-3'>
            <label className='flex items-center gap-2 text-sm text-gray-600 cursor-pointer'>
              <input type='checkbox' checked={showInactive} onChange={e => setShowInactive(e.target.checked)} className='rounded' />
              Inaktive anzeigen
            </label>
            {isManager && (
              <button onClick={openCreate}
                className='px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700'>
                + Neues Projekt
              </button>
            )}
          </div>
        </div>

        {/* Projektkarten */}
        {projects.length === 0 ? (
          <div className='bg-white rounded-xl border border-gray-200 p-12 text-center'>
            <p className='text-gray-400 text-sm'>Noch keine Projekte angelegt.</p>
            {isManager && (
              <button onClick={openCreate} className='mt-3 text-blue-600 text-sm hover:underline'>
                Erstes Projekt erstellen
              </button>
            )}
          </div>
        ) : (
          <div className='grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4'>
            {projects.map(p => {
              const s = getSummary(p.id)
              return (
                <div key={p.id}
                  className={`bg-white rounded-xl border shadow-sm p-5 space-y-3 ${!p.is_active ? 'opacity-60' : 'border-gray-200'}`}>

                  {/* Farbbalken + Name */}
                  <div className='flex items-start gap-3'>
                    <div className='w-3 h-3 rounded-full mt-1 shrink-0' style={{ backgroundColor: p.color }} />
                    <div className='flex-1 min-w-0'>
                      <h3 className='font-semibold text-gray-800 truncate'>{p.name}</h3>
                      {p.description && (
                        <p className='text-xs text-gray-400 mt-0.5 line-clamp-2'>{p.description}</p>
                      )}
                    </div>
                    {!p.is_active && (
                      <span className='text-xs bg-gray-100 text-gray-500 px-2 py-0.5 rounded-full'>Inaktiv</span>
                    )}
                  </div>

                  {/* Stunden */}
                  {s && (
                    <div>
                      <p className='text-2xl font-bold text-gray-900'>{s.total_hours}h</p>
                      <p className='text-xs text-gray-400'>{s.entry_count} Einträge (genehmigt)</p>
                      {s.budget_hours && (
                        <BudgetBar used={s.total_hours} budget={s.budget_hours} />
                      )}
                    </div>
                  )}
                  {!s && p.budget_hours && (
                    <p className='text-xs text-gray-400'>Budget: {p.budget_hours}h</p>
                  )}

                  {/* Aktionen */}
                  {isManager && (
                    <div className='flex gap-2 pt-1 border-t border-gray-100'>
                      <button onClick={() => openEdit(p)}
                        className='text-xs text-blue-600 hover:underline'>
                        Bearbeiten
                      </button>
                      {p.is_active ? (
                        <button onClick={() => deactivate(p)}
                          className='text-xs text-gray-400 hover:text-red-600 hover:underline ml-auto'>
                          Deaktivieren
                        </button>
                      ) : (
                        <button onClick={() => reactivate(p)}
                          className='text-xs text-green-600 hover:underline ml-auto'>
                          Reaktivieren
                        </button>
                      )}
                    </div>
                  )}
                </div>
              )
            })}
          </div>
        )}

        {/* Gesamt-Summary für Manager */}
        {isManager && summary.length > 0 && (
          <div className='bg-white rounded-xl border border-gray-200 shadow-sm'>
            <div className='px-5 py-4 border-b border-gray-100'>
              <h2 className='text-base font-semibold text-gray-800'>Gesamtübersicht (genehmigte Stunden)</h2>
            </div>
            <div className='divide-y divide-gray-50'>
              {summary.map(s => (
                <div key={s.project_id} className='flex items-center gap-3 px-5 py-3'>
                  <div className='w-2.5 h-2.5 rounded-full shrink-0' style={{ backgroundColor: s.project_color }} />
                  <span className='flex-1 text-sm text-gray-700'>{s.project_name}</span>
                  {s.budget_hours && (
                    <div className='w-32'>
                      <BudgetBar used={s.total_hours} budget={s.budget_hours} />
                    </div>
                  )}
                  <span className='text-sm font-semibold text-gray-800 w-16 text-right'>{s.total_hours}h</span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Modal: Erstellen / Bearbeiten */}
      {modal && (
        <div className='fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4'>
          <div className='bg-white rounded-xl shadow-xl w-full max-w-md p-6 space-y-4'>
            <h2 className='text-lg font-semibold text-gray-800'>
              {modal === 'create' ? 'Neues Projekt' : 'Projekt bearbeiten'}
            </h2>

            {error && <div className='bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-700'>{error}</div>}

            <div>
              <label className='block text-sm font-medium text-gray-700 mb-1'>Name *</label>
              <input type='text' value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))}
                placeholder='z.B. Website-Redesign' className={inp} autoFocus />
            </div>

            <div>
              <label className='block text-sm font-medium text-gray-700 mb-1'>Beschreibung</label>
              <textarea value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))}
                rows={2} placeholder='Optionale Projektbeschreibung' className={inp} />
            </div>

            <div>
              <label className='block text-sm font-medium text-gray-700 mb-2'>Farbe</label>
              <div className='flex flex-wrap gap-2'>
                {COLORS.map(c => (
                  <button key={c} type='button' onClick={() => setForm(f => ({ ...f, color: c }))}
                    className={`w-7 h-7 rounded-full border-2 transition-transform ${form.color === c ? 'border-gray-800 scale-110' : 'border-transparent'}`}
                    style={{ backgroundColor: c }} />
                ))}
                <input type='color' value={form.color} onChange={e => setForm(f => ({ ...f, color: e.target.value }))}
                  className='w-7 h-7 rounded cursor-pointer border border-gray-200' title='Eigene Farbe' />
              </div>
            </div>

            <div>
              <label className='block text-sm font-medium text-gray-700 mb-1'>Stundenbudget (optional)</label>
              <input type='number' value={form.budget_hours} onChange={e => setForm(f => ({ ...f, budget_hours: e.target.value }))}
                placeholder='z.B. 40' min='0.1' step='0.5' className={inp} />
              <p className='text-xs text-gray-400 mt-1'>Fortschrittsbalken wird angezeigt wenn Budget gesetzt.</p>
            </div>

            <div className='flex gap-2 pt-2'>
              <button onClick={save} disabled={saving || !form.name.trim()}
                className='flex-1 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 disabled:opacity-50'>
                {saving ? 'Speichern…' : 'Speichern'}
              </button>
              <button onClick={() => setModal(null)}
                className='px-4 py-2 border border-gray-300 text-gray-700 rounded-lg text-sm hover:bg-gray-50'>
                Abbrechen
              </button>
            </div>
          </div>
        </div>
      )}
    </Layout>
  )
}
