'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { EditableText } from '@/components/EditableText';

export default function LoginPage() {
  const router = useRouter();

  const [memberNumber, setMemberNumber] = useState('');
  const [password, setPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isEnabled, setIsEnabled] = useState(true);

  // Check if member authentication is enabled
  useEffect(() => {
    const checkSettings = async () => {
      try {
        const response = await fetch('/api/member-login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ memberNumber: '', password: '' }),
        });

        if (response.status === 403) {
          setIsEnabled(false);
        }
      } catch {
        // Silently fail, assume enabled
      }
    };

    checkSettings();
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!memberNumber || !password) {
      setError('Bitte geben Sie Ihre Mitgliedsnummer und Ihr Passwort ein');
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch('/api/member-login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ memberNumber, password }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Anmeldung fehlgeschlagen');
      }

      // Redirect to voting page with token
      router.push(data.voteUrl);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Ein Fehler ist aufgetreten');
    } finally {
      setIsLoading(false);
    }
  };

  if (!isEnabled) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="mb-8">
          <h1 className="text-2xl font-bold text-[#0057a6] mb-4">MITGLIEDERANMELDUNG</h1>

          <div className="ssvc-main-content">
            <div className="text-center p-6">
              <div className="mb-4 text-red-600">
                Die Mitgliederanmeldung ist derzeit deaktiviert.
              </div>

              <Link href="/" className="ssvc-button inline-block">
                Zurück zur Startseite
              </Link>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-[#0057a6] mb-4">MITGLIEDERANMELDUNG</h1>

        <div className="ssvc-main-content">
          <div className="mb-6">
            <EditableText id="current-vote-text" />
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label htmlFor="memberNumber" className="block text-sm font-medium text-gray-700 mb-1">
                Mitgliedsnummer
              </label>
              <input
                type="text"
                id="memberNumber"
                value={memberNumber}
                onChange={(e) => setMemberNumber(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 focus:outline-none focus:border-[#0057a6]"
                required
              />
            </div>

            <div>
              <label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
                Passwort
              </label>
              <input
                type="password"
                id="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 focus:outline-none focus:border-[#0057a6]"
                required
              />
            </div>

            {error && (
              <div className="text-red-500 text-sm">{error}</div>
            )}

            <button
              type="submit"
              disabled={isLoading}
              className="ssvc-button w-full disabled:opacity-50"
            >
              {isLoading ? 'Anmelden...' : 'Anmelden'}
            </button>
          </form>

          <div className="mt-6 text-center">
            <Link href="/" className="text-[#0057a6] hover:underline">
              Zurück zur Startseite
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
