import { useEffect, useState } from 'react';
import {
  Button, Input, Toggle, FormField, SectionHeader, Tag, ConfirmDialog, Alert,
} from '@cameleer/design-system';
import { useToast } from '@cameleer/design-system';
import { adminFetch } from '../../api/queries/admin/admin-api';
import styles from './OidcConfigPage.module.css';
import sectionStyles from '../../styles/section-card.module.css';

interface OidcFormData {
  enabled: boolean;
  autoSignup: boolean;
  issuerUri: string;
  clientId: string;
  clientSecret: string;
  rolesClaim: string;
  displayNameClaim: string;
  userIdClaim: string;
  defaultRoles: string[];
  audience: string;
  additionalScopes: string[];
}

const EMPTY_CONFIG: OidcFormData = {
  enabled: false,
  autoSignup: true,
  issuerUri: '',
  clientId: '',
  clientSecret: '',
  rolesClaim: 'roles',
  displayNameClaim: 'name',
  userIdClaim: 'sub',
  defaultRoles: ['VIEWER'],
  audience: '',
  additionalScopes: [],
};

export default function OidcConfigPage() {
  const [form, setForm] = useState<OidcFormData | null>(null);
  const [newRole, setNewRole] = useState('');
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const { toast } = useToast();

  useEffect(() => {
    adminFetch<Partial<OidcFormData> & { configured?: boolean }>('/oidc')
      .then((data) => setForm({
        enabled: data.enabled ?? false,
        autoSignup: data.autoSignup ?? true,
        issuerUri: data.issuerUri ?? '',
        clientId: data.clientId ?? '',
        clientSecret: data.clientSecret ?? '',
        rolesClaim: data.rolesClaim ?? 'roles',
        displayNameClaim: data.displayNameClaim ?? 'name',
        userIdClaim: data.userIdClaim ?? 'sub',
        defaultRoles: data.defaultRoles ?? ['VIEWER'],
        audience: (data as any).audience ?? '',
        additionalScopes: (data as any).additionalScopes ?? [],
      }))
      .catch(() => setForm(EMPTY_CONFIG));
  }, []);

  function update<K extends keyof OidcFormData>(key: K, value: OidcFormData[K]) {
    setForm((prev) => prev ? { ...prev, [key]: value } : prev);
  }

  function addRole() {
    if (!form) return;
    const role = newRole.trim().toUpperCase();
    if (role && !(form.defaultRoles || []).includes(role)) {
      update('defaultRoles', [...(form.defaultRoles || []), role]);
      setNewRole('');
    }
  }

  function removeRole(role: string) {
    if (!form) return;
    update('defaultRoles', (form.defaultRoles || []).filter((r) => r !== role));
  }

  async function handleSave() {
    if (!form) return;
    setSaving(true);
    setError(null);
    try {
      await adminFetch('/oidc', { method: 'PUT', body: JSON.stringify(form) });
      toast({ title: 'Settings saved', description: 'OIDC configuration updated successfully.', variant: 'success' });
    } catch (e: any) {
      setError(e.message);
      toast({ title: 'Save failed', description: e.message, variant: 'error', duration: 86_400_000 });
    } finally {
      setSaving(false);
    }
  }

  async function handleTest() {
    if (!form) return;
    setTesting(true);
    setError(null);
    try {
      const result = await adminFetch<{ status: string; authorizationEndpoint?: string }>('/oidc/test', { method: 'POST' });
      toast({ title: 'Connection test', description: `OIDC provider responded: ${result.status}`, variant: 'success' });
    } catch (e: any) {
      setError(e.message);
      toast({ title: 'Connection test failed', description: e.message, variant: 'error', duration: 86_400_000 });
    } finally {
      setTesting(false);
    }
  }

  async function handleDelete() {
    setDeleteOpen(false);
    setError(null);
    try {
      await adminFetch('/oidc', { method: 'DELETE' });
      setForm(EMPTY_CONFIG);
      toast({ title: 'Configuration deleted', description: 'OIDC configuration has been removed.', variant: 'warning' });
    } catch (e: any) {
      setError(e.message);
      toast({ title: 'Delete failed', description: e.message, variant: 'error', duration: 86_400_000 });
    }
  }

  if (!form) return null;

  return (
    <div className={styles.page}>
      <div className={styles.toolbar}>
        <Button size="sm" variant="secondary" onClick={handleTest} disabled={!form.issuerUri || testing}>
          {testing ? 'Testing...' : 'Test Connection'}
        </Button>
        <Button size="sm" variant="primary" onClick={handleSave} disabled={saving}>
          {saving ? 'Saving...' : 'Save'}
        </Button>
      </div>

      {error && <div style={{ marginBottom: 16 }}><Alert variant="error">{error}</Alert></div>}

      <section className={sectionStyles.section}>
        <SectionHeader>Behavior</SectionHeader>
        <div className={styles.toggleRow}>
          <Toggle
            label="Enabled"
            checked={form.enabled}
            onChange={(e) => update('enabled', e.target.checked)}
          />
        </div>
        <div className={styles.toggleRow}>
          <Toggle
            label="Auto Sign-Up"
            checked={form.autoSignup}
            onChange={(e) => update('autoSignup', e.target.checked)}
          />
          <span className={styles.hint}>Automatically create accounts for new OIDC users</span>
        </div>
      </section>

      <section className={sectionStyles.section}>
        <SectionHeader>Provider Settings</SectionHeader>
        <FormField label="Issuer URI" htmlFor="issuer">
          <Input
            id="issuer"
            type="url"
            placeholder="https://idp.example.com/realms/my-realm"
            value={form.issuerUri}
            onChange={(e) => update('issuerUri', e.target.value)}
          />
        </FormField>
        <FormField label="Client ID" htmlFor="client-id">
          <Input
            id="client-id"
            value={form.clientId}
            onChange={(e) => update('clientId', e.target.value)}
          />
        </FormField>
        <FormField label="Client Secret" htmlFor="client-secret">
          <Input
            id="client-secret"
            type="password"
            value={form.clientSecret}
            onChange={(e) => update('clientSecret', e.target.value)}
          />
        </FormField>
        <FormField label="Audience / API Resource" htmlFor="audience" hint="RFC 8707 resource indicator sent in the authorization request">
          <Input
            id="audience"
            placeholder="https://api.example.com"
            value={form.audience}
            onChange={(e) => update('audience', e.target.value)}
          />
        </FormField>
        <FormField label="Additional Scopes" htmlFor="additional-scopes" hint="Extra scopes to request beyond openid email profile (comma-separated)">
          <Input
            id="additional-scopes"
            placeholder="urn:scope:organizations, urn:scope:roles"
            value={(form.additionalScopes || []).join(', ')}
            onChange={(e) => update('additionalScopes', e.target.value.split(',').map(s => s.trim()).filter(Boolean))}
          />
        </FormField>
      </section>

      <section className={sectionStyles.section}>
        <SectionHeader>Claim Mapping</SectionHeader>
        <FormField label="Roles Claim" htmlFor="roles-claim" hint="JSON path to roles in the access token or ID token">
          <Input
            id="roles-claim"
            value={form.rolesClaim}
            onChange={(e) => update('rolesClaim', e.target.value)}
          />
        </FormField>
        <FormField label="User ID Claim" htmlFor="userid-claim" hint="Claim used as unique user identifier (default: sub)">
          <Input
            id="userid-claim"
            value={form.userIdClaim}
            onChange={(e) => update('userIdClaim', e.target.value)}
          />
        </FormField>
        <FormField label="Display Name Claim" htmlFor="name-claim" hint="Claim used for user display name">
          <Input
            id="name-claim"
            value={form.displayNameClaim}
            onChange={(e) => update('displayNameClaim', e.target.value)}
          />
        </FormField>
      </section>

      <section className={sectionStyles.section}>
        <SectionHeader>Default Roles</SectionHeader>
        <div className={styles.tagList}>
          {(form.defaultRoles || []).map((role) => (
            <Tag key={role} label={role} color="primary" onRemove={() => removeRole(role)} />
          ))}
          {(form.defaultRoles || []).length === 0 && (
            <span className={styles.noRoles}>No default roles configured</span>
          )}
        </div>
        <div className={styles.addRoleRow}>
          <Input
            placeholder="Add role..."
            value={newRole}
            onChange={(e) => setNewRole(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addRole(); } }}
            className={styles.roleInput}
          />
          <Button size="sm" variant="secondary" onClick={addRole} disabled={!newRole.trim()}>
            Add
          </Button>
        </div>
      </section>

      <section className={sectionStyles.section}>
        <SectionHeader>Danger Zone</SectionHeader>
        <Button size="sm" variant="danger" onClick={() => setDeleteOpen(true)}>
          Delete OIDC Configuration
        </Button>
        <ConfirmDialog
          open={deleteOpen}
          onClose={() => setDeleteOpen(false)}
          onConfirm={handleDelete}
          message="Delete OIDC configuration? All users signed in via OIDC will lose access."
          confirmText="delete oidc"
          loading={saving}
        />
      </section>
    </div>
  );
}
