import React, { useState } from 'react'
import { api } from '../../utils/api'

function AssignmentsTab({ styleDirections, targetGroups, assignments, loading, error, onUpdate }) {
  const [saving, setSaving] = useState(false)

  if (loading) {
    return (
      <div className="empty-state" style={{ padding: '2.5rem' }}>
        <div className="spinner" />
      </div>
    )
  }

  async function toggleAssignment(styleDirectionId, targetGroupId, currentlyAssigned) {
    setSaving(true)
    try {
      if (currentlyAssigned) {
        const assignment = assignments.find(
          (a) => a.style_direction_id === styleDirectionId && a.target_group_id === targetGroupId
        )
        if (assignment) {
          await api.deleteStyleDirectionTargetGroup(assignment.id)
        }
      } else {
        await api.createStyleDirectionTargetGroup({
          style_direction_id: styleDirectionId,
          target_group_id: targetGroupId,
          is_primary: false
        })
      }
      onUpdate()
    } catch (e) {
      alert('Fehler: ' + e.message)
    } finally {
      setSaving(false)
    }
  }

  function isAssigned(styleDirectionId, targetGroupId) {
    return assignments.some(
      (a) => a.style_direction_id === styleDirectionId && a.target_group_id === targetGroupId
    )
  }

  const groupedStyles = styleDirections.reduce((acc, sd) => {
    const key = sd.focus_area_name || 'Ohne Fokusbereich'
    if (!acc[key]) acc[key] = []
    acc[key].push(sd)
    return acc
  }, {})

  return (
    <div className="admin-assignments-wrap">
      <h2 className="admin-assignments-wrap__title">Zuordnungen: Stilrichtungen ↔ Zielgruppen</h2>
      {error && <div className="admin-matrix-alert">{error}</div>}

      {targetGroups.length === 0 && (
        <div className="empty-state" style={{ padding: '2rem 1rem' }}>
          Keine Zielgruppen vorhanden. Bitte zuerst unter <strong>Kataloge</strong> anlegen.
        </div>
      )}

      {styleDirections.length === 0 && (
        <div className="empty-state" style={{ padding: '2rem 1rem' }}>
          Keine Stilrichtungen vorhanden. Bitte zuerst unter <strong>Hierarchie</strong> anlegen.
        </div>
      )}

      {targetGroups.length > 0 && styleDirections.length > 0 && (
        <div className="admin-assignments-matrix-container">
          <table className="admin-assignments-matrix">
            <thead>
              <tr>
                <th className="admin-assignments-matrix__corner">Stilrichtung</th>
                {targetGroups.map((tg) => (
                  <th key={tg.id} className="admin-assignments-matrix__th-narrow">
                    {tg.name}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {Object.entries(groupedStyles).map(([focusAreaName, styles]) => (
                <React.Fragment key={focusAreaName}>
                  <tr>
                    <td
                      className="admin-assignments-matrix__focus-header"
                      colSpan={targetGroups.length + 1}
                    >
                      {focusAreaName}
                    </td>
                  </tr>
                  {styles.map((sd) => (
                    <tr key={sd.id}>
                      <td className="admin-assignments-matrix__row-label">{sd.name}</td>
                      {targetGroups.map((tg) => {
                        const assigned = isAssigned(sd.id, tg.id)
                        return (
                          <td key={tg.id} style={{ textAlign: 'center', padding: '12px' }}>
                            <input
                              type="checkbox"
                              checked={assigned}
                              onChange={() => toggleAssignment(sd.id, tg.id, assigned)}
                              disabled={saving}
                              aria-label={`${sd.name} — ${tg.name}`}
                              style={{ width: '20px', height: '20px', cursor: 'pointer', accentColor: 'var(--accent)' }}
                            />
                          </td>
                        )
                      })}
                    </tr>
                  ))}
                </React.Fragment>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}

export default AssignmentsTab
