'use client';

import { useEffect, useState } from 'react';
import type { Kuppel, ArtFuehrung, BeoOption, SelectedObjekt, Wetter, LogbuchEintrag } from '@/types/logbuch';
import { ARTEN } from '@/types/logbuch';
import BeoSelector from './BeoSelector';
import ObjektSelector from './ObjektSelector';

interface Props {
  kuppel: Kuppel;
  currentUserBeo: BeoOption;
  editEntry?: LogbuchEintrag | null;
  onSaved: () => void;
}

function toLocalDatetimeValue(isoOrDatetime: string): string {
  if (!isoOrDatetime) return '';
  return isoOrDatetime.slice(0, 16);
}

function nowLocalDatetime(): string {
  const now = new Date();
  const pad = (n: number) => String(n).padStart(2, '0');
  return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}T${pad(now.getHours())}:${pad(now.getMinutes())}`;
}

export default function LogbuchForm({ kuppel, currentUserBeo, editEntry, onSaved }: Props) {
  const [artFuehrung, setArtFuehrung] = useState<ArtFuehrung>('Reguläre Führung');
  const [beginn, setBeginn] = useState(nowLocalDatetime());
  const [ende, setEnde] = useState(nowLocalDatetime());
  const [besucher, setBesucher] = useState(0);
  const [beos, setBeos] = useState<BeoOption[]>([currentUserBeo]);
  const [objekte, setObjekte] = useState<SelectedObjekt[]>([]);
  const [bemerkungen, setBemerkungen] = useState('');
  const [wetter, setWetter] = useState<Wetter | null>(null);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);

  useEffect(() => {
    fetch('/api/wetter')
      .then((r) => { if (!r.ok) throw new Error(); return r.json(); })
      .then(setWetter)
      .catch(() => {});
  }, []);

  useEffect(() => {
    if (editEntry) {
      setArtFuehrung(editEntry.ArtFuehrung);
      setBeginn(toLocalDatetimeValue(editEntry.Beginn));
      setEnde(toLocalDatetimeValue(editEntry.Ende));
      setBesucher(editEntry.Besucher);
      setBemerkungen(editEntry.Bemerkungen ?? '');
      if (editEntry.WetterTemp !== null) {
        setWetter({
          temp: editEntry.WetterTemp ?? 0,
          feuchte: editEntry.WetterFeuchte ?? 0,
          druck: editEntry.WetterDruck ?? 0,
        });
      }
    } else {
      setArtFuehrung('Reguläre Führung');
      setBeginn(nowLocalDatetime());
      setEnde(nowLocalDatetime());
      setBesucher(0);
      setBeos([currentUserBeo]);
      setObjekte([]);
      setBemerkungen('');
    }
  }, [editEntry, currentUserBeo]);

  useEffect(() => {
    if (editEntry && editEntry.BEOs) {
      fetch('/api/beos')
        .then((r) => r.json())
        .then((all: BeoOption[]) => {
          const kuerzel = editEntry.BEOs.split(', ').map((k) => k.trim());
          setBeos(all.filter((b) => kuerzel.includes(b.Kuerzel)));
        })
        .catch(() => {});
    }
    if (editEntry && editEntry.Objekte) {
      const names = editEntry.Objekte.split(', ').map((n) => n.trim());
      fetch('/api/objekte')
        .then((r) => r.json())
        .then((all: { ID: number; Name: string }[]) => {
          const result: SelectedObjekt[] = names.map((name) => {
            const found = all.find((o) => o.Name === name);
            return { ID: found?.ID ?? null, Name: name };
          });
          setObjekte(result);
        })
        .catch(() => {});
    }
  }, [editEntry]);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setError('');
    setSuccess(false);

    const body = {
      Kuppel: kuppel,
      ArtFuehrung: artFuehrung,
      Beginn: beginn,
      Ende: ende,
      Besucher: besucher,
      beoIds: beos.map((b) => b.ID),
      objekte,
      Bemerkungen: bemerkungen,
      Wetter: wetter,
    };

    const url = editEntry ? `/api/logbuch/${editEntry.ID}` : '/api/logbuch';
    const method = editEntry ? 'PUT' : 'POST';

    try {
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      if (!res.ok) throw new Error(await res.text());
      setSuccess(true);
      if (!editEntry) {
        setBeginn(nowLocalDatetime());
        setEnde(nowLocalDatetime());
        setBesucher(0);
        setBeos([currentUserBeo]);
        setObjekte([]);
        setBemerkungen('');
      }
      onSaved();
    } catch {
      setError('Fehler beim Speichern. Bitte erneut versuchen.');
    } finally {
      setSaving(false);
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4 max-w-2xl">
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Art der Führung</label>
          <select
            value={artFuehrung}
            onChange={(e) => setArtFuehrung(e.target.value as ArtFuehrung)}
            className="w-full px-3 py-2 border-2 border-gray-400 rounded-lg bg-white text-sm focus:border-blue-500 focus:outline-none"
          >
            {ARTEN.map((a) => (
              <option key={a} value={a}>{a}</option>
            ))}
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Kuppel</label>
          <input
            type="text"
            value={kuppel}
            readOnly
            className="w-full px-3 py-2 border-2 border-gray-300 rounded-lg bg-gray-100 text-sm text-gray-600"
          />
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Beginn</label>
          <input
            type="datetime-local"
            value={beginn}
            onChange={(e) => setBeginn(e.target.value)}
            required
            className="w-full px-3 py-2 border-2 border-gray-400 rounded-lg bg-white text-sm focus:border-blue-500 focus:outline-none"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Ende</label>
          <input
            type="datetime-local"
            value={ende}
            onChange={(e) => setEnde(e.target.value)}
            required
            className="w-full px-3 py-2 border-2 border-gray-400 rounded-lg bg-white text-sm focus:border-blue-500 focus:outline-none"
          />
        </div>
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">Anzahl Besucher</label>
        <input
          type="number"
          value={besucher}
          onChange={(e) => setBesucher(parseInt(e.target.value) || 0)}
          min={0}
          max={9999}
          className="w-32 px-3 py-2 border-2 border-gray-400 rounded-lg bg-white text-sm focus:border-blue-500 focus:outline-none"
        />
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">BEOs</label>
        <BeoSelector selected={beos} onChange={setBeos} />
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">Beobachtete Objekte</label>
        <ObjektSelector selected={objekte} onChange={setObjekte} />
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          Bemerkungen
          <span className="ml-2 text-gray-400 font-normal text-xs">({bemerkungen.length}/500)</span>
        </label>
        <textarea
          value={bemerkungen}
          onChange={(e) => setBemerkungen(e.target.value.slice(0, 500))}
          rows={3}
          className="w-full px-3 py-2 border-2 border-gray-400 rounded-lg bg-white text-sm focus:border-blue-500 focus:outline-none resize-y"
          placeholder="Freier Text (max. 500 Zeichen)"
        />
      </div>

      {wetter && (
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Wetter (aktuell)</label>
          <div className="flex gap-4 text-sm text-gray-600 bg-gray-50 border border-gray-200 rounded-lg px-3 py-2">
            <span>🌡 {wetter.temp} °C</span>
            <span>💧 {wetter.feuchte} %</span>
            <span>🌬 {wetter.druck} hPa</span>
          </div>
        </div>
      )}

      {error && (
        <div className="bg-red-50 border border-red-300 text-red-700 px-3 py-2 rounded-lg text-sm">
          {error}
        </div>
      )}
      {success && !editEntry && (
        <div className="bg-green-50 border border-green-300 text-green-700 px-3 py-2 rounded-lg text-sm">
          Eintrag gespeichert.
        </div>
      )}

      <div className="flex gap-3">
        <button
          type="submit"
          disabled={saving}
          className="px-6 py-2 bg-[#85B7D7] hover:bg-[#6a9fc5] text-black font-medium rounded-lg transition-colors disabled:opacity-50 text-sm"
        >
          {saving ? 'Speichern...' : editEntry ? 'Änderungen speichern' : 'Eintrag speichern'}
        </button>
        {editEntry && (
          <button
            type="button"
            onClick={onSaved}
            className="px-6 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 font-medium rounded-lg transition-colors text-sm"
          >
            Abbrechen
          </button>
        )}
      </div>
    </form>
  );
}
