'use client';

import { useState, useEffect } from 'react';
import { useApi } from '@/lib/useApi';
import { SetPageHeader } from '@/components/layout/SetPageHeader';
import {
  createHousehold,
  joinHousehold,
  getHousehold,
  updateHousehold,
  generateInviteCode,
} from '@/services/households';

export default function SettingsPage() {
  const { householdId, isLoading, refreshProfile } = useApi();

  if (isLoading) {
    return (
      <>
        <SetPageHeader title="Settings" subtitle="Household and account" />
        <SettingsLoading />
      </>
    );
  }

  return (
    <>
      <SetPageHeader title="Settings" subtitle="Household and account" />
      <div style={{ padding: '28px 32px 56px' }}>
        <div style={{ maxWidth: 640, display: 'flex', flexDirection: 'column', gap: 24 }}>
          <HouseholdSection householdId={householdId} onHouseholdChanged={() => refreshProfile()} />
          <AccountSection />
        </div>
      </div>
    </>
  );
}

function SettingsLoading() {
  return (
    <div style={{ padding: '28px 32px' }}>
      <div style={{ maxWidth: 640 }}>
        <div style={{ height: 192, borderRadius: 'var(--r-md)', background: 'var(--bg-inset)' }} />
      </div>
    </div>
  );
}

function HouseholdSection({
  householdId,
  onHouseholdChanged,
}: {
  householdId: string | null;
  onHouseholdChanged: () => void;
}) {
  const [householdName, setHouseholdName] = useState('');
  const [inviteCode, setInviteCode] = useState('');
  const [error, setError] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [currentHousehold, setCurrentHousehold] = useState<{
    name: string;
    inviteCode: string;
    members: { userId: string; role: string }[];
  } | null>(null);
  const [loadedHousehold, setLoadedHousehold] = useState(false);

  const [editingName, setEditingName] = useState(false);
  const [editedName, setEditedName] = useState('');
  const [editNameError, setEditNameError] = useState('');
  const [savingName, setSavingName] = useState(false);
  const [regenerating, setRegenerating] = useState(false);
  const [regenerateError, setRegenerateError] = useState('');

  useEffect(() => {
    if (!householdId || loadedHousehold) return;
    let cancelled = false;
    async function loadHousehold() {
      try {
        const hh = await getHousehold(householdId as string);
        if (!cancelled) setCurrentHousehold(hh);
      } catch {
        // Household may not be accessible yet
      }
      if (!cancelled) setLoadedHousehold(true);
    }
    void loadHousehold();
    return () => {
      cancelled = true;
    };
  }, [householdId, loadedHousehold]);

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    setError('');
    setSubmitting(true);
    try {
      await createHousehold(householdName.trim());
      setHouseholdName('');
      onHouseholdChanged();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create household');
    } finally {
      setSubmitting(false);
    }
  }

  async function handleJoin(e: React.FormEvent) {
    e.preventDefault();
    setError('');
    setSubmitting(true);
    try {
      await joinHousehold(inviteCode.trim());
      setInviteCode('');
      onHouseholdChanged();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to join household');
    } finally {
      setSubmitting(false);
    }
  }

  async function handleSaveName() {
    if (!householdId || /* v8 ignore next */ !currentHousehold) return;
    const trimmed = editedName.trim();
    if (!trimmed) {
      setEditNameError('Name cannot be empty');
      return;
    }
    if (trimmed === currentHousehold.name) {
      setEditingName(false);
      setEditNameError('');
      return;
    }
    setEditNameError('');
    setSavingName(true);
    try {
      const updated = await updateHousehold(householdId, { name: trimmed });
      setCurrentHousehold(updated);
      setEditingName(false);
    } catch (err) {
      setEditNameError(err instanceof Error ? err.message : 'Failed to update name');
    } finally {
      setSavingName(false);
    }
  }

  async function handleRegenerateInviteCode() {
    if (!householdId) return;
    setRegenerateError('');
    setRegenerating(true);
    try {
      const updated = await generateInviteCode(householdId);
      setCurrentHousehold(updated);
    } catch (err) {
      setRegenerateError(err instanceof Error ? err.message : 'Failed to regenerate invite code');
    } finally {
      setRegenerating(false);
    }
  }

  if (householdId) {
    return (
      <section className="rounded-xl border bg-white p-6 shadow-sm">
        <h2 className="text-lg font-semibold mb-4">Household</h2>
        {currentHousehold ? (
          <div className="space-y-3">
            <div>
              <span className="text-sm text-gray-500">Name:</span>{' '}
              {editingName ? (
                <span className="inline-flex items-center gap-2">
                  <input
                    type="text"
                    value={editedName}
                    onChange={(e) => setEditedName(e.target.value)}
                    maxLength={100}
                    className="rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                  />
                  <button
                    type="button"
                    onClick={handleSaveName}
                    disabled={savingName}
                    className="rounded-lg bg-primary-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-primary-700 disabled:opacity-50 transition-colors"
                  >
                    {savingName ? 'Saving...' : 'Save'}
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      setEditingName(false);
                      setEditNameError('');
                    }}
                    disabled={savingName}
                    className="rounded-lg border px-3 py-1.5 text-xs font-medium hover:bg-gray-50 disabled:opacity-50 transition-colors"
                  >
                    Cancel
                  </button>
                </span>
              ) : (
                <span className="inline-flex items-center gap-2">
                  <span className="font-medium">{currentHousehold.name}</span>
                  <button
                    type="button"
                    onClick={() => {
                      setEditedName(currentHousehold.name);
                      setEditNameError('');
                      setEditingName(true);
                    }}
                    className="rounded-lg border px-2 py-1 text-xs font-medium text-gray-600 hover:bg-gray-50 transition-colors"
                  >
                    Edit
                  </button>
                </span>
              )}
              {editNameError && <p className="mt-1 text-xs text-red-600">{editNameError}</p>}
            </div>
            <div>
              <span className="text-sm text-gray-500">Invite Code:</span>{' '}
              <span className="inline-flex items-center gap-2">
                <code className="rounded bg-gray-100 px-2 py-1 text-sm font-mono">
                  {currentHousehold.inviteCode}
                </code>
                <button
                  type="button"
                  onClick={handleRegenerateInviteCode}
                  disabled={regenerating}
                  className="rounded-lg border px-2 py-1 text-xs font-medium text-gray-600 hover:bg-gray-50 disabled:opacity-50 transition-colors"
                >
                  {regenerating ? 'Regenerating...' : 'Regenerate'}
                </button>
              </span>
              {regenerateError && <p className="mt-1 text-xs text-red-600">{regenerateError}</p>}
            </div>
            <div>
              <span className="text-sm text-gray-500">Members:</span>{' '}
              <span className="font-medium">{currentHousehold.members.length}</span>
            </div>
          </div>
        ) : (
          <p className="text-sm text-gray-500">Loading household details...</p>
        )}
      </section>
    );
  }

  return (
    <section className="rounded-xl border bg-white p-6 shadow-sm">
      <h2 className="text-lg font-semibold mb-4">Household</h2>
      <p className="text-sm text-gray-500 mb-4">
        You are not part of any household yet. Create one or join using an invite code.
      </p>

      {error && (
        <div className="mb-4 rounded-lg bg-red-50 border border-red-200 p-3 text-sm text-red-700">
          {error}
        </div>
      )}

      <div className="space-y-6">
        <form onSubmit={handleCreate} className="space-y-3">
          <h3 className="text-sm font-medium text-gray-700">Create a new household</h3>
          <div className="flex gap-3">
            <input
              type="text"
              value={householdName}
              onChange={(e) => setHouseholdName(e.target.value)}
              placeholder="Household name"
              required
              maxLength={100}
              className="flex-1 rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
            />
            <button
              type="submit"
              disabled={submitting || !householdName.trim()}
              className="rounded-lg bg-primary-600 px-4 py-2 text-sm font-medium text-white hover:bg-primary-700 disabled:opacity-50 transition-colors"
            >
              Create
            </button>
          </div>
        </form>

        <div className="border-t" />

        <form onSubmit={handleJoin} className="space-y-3">
          <h3 className="text-sm font-medium text-gray-700">Join with invite code</h3>
          <div className="flex gap-3">
            <input
              type="text"
              value={inviteCode}
              onChange={(e) => setInviteCode(e.target.value)}
              placeholder="Invite code"
              required
              className="flex-1 rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
            />
            <button
              type="submit"
              disabled={submitting || !inviteCode.trim()}
              className="rounded-lg border px-4 py-2 text-sm font-medium hover:bg-gray-50 disabled:opacity-50 transition-colors"
            >
              Join
            </button>
          </div>
        </form>
      </div>
    </section>
  );
}

function AccountSection() {
  const keycloakUrl = process.env.NEXT_PUBLIC_KEYCLOAK_URL || 'http://localhost:8080';
  const realm = process.env.NEXT_PUBLIC_KEYCLOAK_REALM || 'meshitrack';

  return (
    <section className="rounded-xl border bg-white p-6 shadow-sm">
      <h2 className="text-lg font-semibold mb-4">Account</h2>
      <p className="text-sm text-gray-500">
        Account settings are managed through Keycloak. Click the button below to manage your
        profile.
      </p>
      <a
        href={`${keycloakUrl}/realms/${realm}/account`}
        target="_blank"
        rel="noopener noreferrer"
        className="mt-4 inline-block rounded-lg border px-4 py-2 text-sm font-medium hover:bg-gray-50 transition-colors"
      >
        Manage Keycloak Account
      </a>
    </section>
  );
}
