'use client'

import { useState } from 'react'
import type { FoundingWizardState, Gesellschafter } from '@/lib/sdk/founding/types'

interface Props {
  state: FoundingWizardState
  addGesellschafter: (g: Omit<Gesellschafter, 'id' | 'anteil_nr'>) => void
  updateGesellschafter: (id: string, p: Partial<Gesellschafter>) => void
  removeGesellschafter: (id: string) => void
}

export function StepGesellschafter({ state, addGesellschafter, updateGesellschafter, removeGesellschafter }: Props) {
  const [form, setForm] = useState({
    name: '', geburtsdatum: '', adresse: '', email: '',
    nennbetrag_eur: 12500, is_geschaeftsfuehrer: true, internal_role: '',
    has_academic_background: false,
  })

  const totalNennbetrag = state.gesellschafter.reduce((s, g) => s + g.nennbetrag_eur, 0)
  const target = state.capital.stammkapital_eur

  const handleAdd = () => {
    if (!form.name.trim()) return
    addGesellschafter({
      rolle: 'founder',
      name: form.name,
      geburtsdatum: form.geburtsdatum || undefined,
      adresse: form.adresse,
      email: form.email || undefined,
      nennbetrag_eur: form.nennbetrag_eur,
      is_geschaeftsfuehrer: form.is_geschaeftsfuehrer,
      internal_role: form.internal_role || undefined,
      has_academic_background: form.has_academic_background,
    })
    setForm({ name: '', geburtsdatum: '', adresse: '', email: '', nennbetrag_eur: 12500,
              is_geschaeftsfuehrer: true, internal_role: '', has_academic_background: false })
  }

  return (
    <div className="space-y-4">
      <div className="bg-gray-50 p-4 rounded-lg">
        <h3 className="font-semibold mb-3">Neuen Gesellschafter hinzufügen</h3>
        <div className="grid grid-cols-2 gap-3">
          <input
            data-testid="gs-name"
            placeholder="Name"
            value={form.name}
            onChange={e => setForm({ ...form, name: e.target.value })}
            className="px-3 py-2 border rounded"
          />
          <input
            data-testid="gs-birthdate"
            type="date"
            placeholder="Geburtsdatum"
            value={form.geburtsdatum}
            onChange={e => setForm({ ...form, geburtsdatum: e.target.value })}
            className="px-3 py-2 border rounded"
          />
          <input
            data-testid="gs-address"
            placeholder="Adresse (Straße, PLZ Ort)"
            value={form.adresse}
            onChange={e => setForm({ ...form, adresse: e.target.value })}
            className="px-3 py-2 border rounded col-span-2"
          />
          <input
            data-testid="gs-email"
            type="email"
            placeholder="E-Mail (optional)"
            value={form.email}
            onChange={e => setForm({ ...form, email: e.target.value })}
            className="px-3 py-2 border rounded"
          />
          <input
            data-testid="gs-nennbetrag"
            type="number"
            min={1}
            step={1}
            placeholder="Nennbetrag in EUR"
            value={form.nennbetrag_eur}
            onChange={e => setForm({ ...form, nennbetrag_eur: parseInt(e.target.value) || 0 })}
            className="px-3 py-2 border rounded"
          />
          <input
            data-testid="gs-role"
            placeholder="Interne Rolle (z.B. CEO, CTO)"
            value={form.internal_role}
            onChange={e => setForm({ ...form, internal_role: e.target.value })}
            className="px-3 py-2 border rounded"
          />
          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              data-testid="gs-is-gf"
              checked={form.is_geschaeftsfuehrer}
              onChange={e => setForm({ ...form, is_geschaeftsfuehrer: e.target.checked })}
            />
            <label className="text-sm">Geschäftsführer/in</label>
          </div>
          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              data-testid="gs-academic"
              checked={form.has_academic_background}
              onChange={e => setForm({ ...form, has_academic_background: e.target.checked })}
            />
            <label className="text-sm">Akademischer Hintergrund</label>
          </div>
        </div>
        <button
          data-testid="add-gesellschafter"
          onClick={handleAdd}
          disabled={!form.name.trim() || form.nennbetrag_eur < 1}
          className="mt-3 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50"
        >
          Gesellschafter hinzufügen
        </button>
      </div>

      <div>
        <h3 className="font-semibold mb-3">Gesellschafter ({state.gesellschafter.length})</h3>
        {state.gesellschafter.length === 0 ? (
          <p className="text-gray-500 text-sm">Noch keine Gesellschafter angelegt.</p>
        ) : (
          <table className="w-full text-sm" data-testid="gs-table">
            <thead className="bg-gray-100">
              <tr>
                <th className="px-3 py-2 text-left">Nr.</th>
                <th className="px-3 py-2 text-left">Name</th>
                <th className="px-3 py-2 text-left">Geburtsdatum</th>
                <th className="px-3 py-2 text-right">Nennbetrag</th>
                <th className="px-3 py-2 text-right">Anteil %</th>
                <th className="px-3 py-2">GF?</th>
                <th className="px-3 py-2"></th>
              </tr>
            </thead>
            <tbody>
              {state.gesellschafter.map(g => (
                <tr key={g.id} className="border-t" data-testid={`gs-row-${g.anteil_nr}`}>
                  <td className="px-3 py-2">{g.anteil_nr}</td>
                  <td className="px-3 py-2 font-medium">{g.name}{g.internal_role ? ` (${g.internal_role})` : ''}</td>
                  <td className="px-3 py-2">{g.geburtsdatum || '—'}</td>
                  <td className="px-3 py-2 text-right">{g.nennbetrag_eur.toLocaleString('de-DE')} €</td>
                  <td className="px-3 py-2 text-right">{((g.nennbetrag_eur / Math.max(target, 1)) * 100).toFixed(2)}%</td>
                  <td className="px-3 py-2 text-center">{g.is_geschaeftsfuehrer ? '✓' : '—'}</td>
                  <td className="px-3 py-2">
                    <button
                      onClick={() => removeGesellschafter(g.id)}
                      className="text-red-600 hover:underline text-xs"
                    >
                      Entfernen
                    </button>
                  </td>
                </tr>
              ))}
              <tr className="border-t-2 font-semibold bg-gray-50">
                <td colSpan={3} className="px-3 py-2">Summe</td>
                <td className="px-3 py-2 text-right" data-testid="gs-total">
                  {totalNennbetrag.toLocaleString('de-DE')} €
                </td>
                <td className="px-3 py-2 text-right">
                  {totalNennbetrag === target ? '100%' : `≠ ${target.toLocaleString('de-DE')} €`}
                </td>
                <td colSpan={2}></td>
              </tr>
            </tbody>
          </table>
        )}
        {totalNennbetrag !== target && state.gesellschafter.length > 0 && (
          <p className="mt-2 text-sm text-orange-600">
            ⚠ Die Summe der Nennbeträge ({totalNennbetrag.toLocaleString('de-DE')} €)
            entspricht nicht dem Stammkapital ({target.toLocaleString('de-DE')} €).
          </p>
        )}
      </div>
    </div>
  )
}
