import { useState, useEffect } from 'react';
import {
  Alert,
  Badge,
  Button,
  Card,
  FormField,
  Input,
  Spinner,
  useToast,
} from '@cameleer/design-system';
import { useTenantOidc, useUpdateOidc } from '../../api/tenant-hooks';
import styles from '../../styles/platform.module.css';

interface OidcFormState {
  issuerUri: string;
  clientId: string;
  clientSecret: string;
  audience: string;
  rolesClaim: string;
}

const EMPTY_FORM: OidcFormState = {
  issuerUri: '',
  clientId: '',
  clientSecret: '',
  audience: '',
  rolesClaim: '',
};

function isExternalOidc(config: Record<string, unknown>): boolean {
  return typeof config['issuerUri'] === 'string' && config['issuerUri'] !== '';
}

export function OidcConfigPage() {
  const { data: oidcConfig, isLoading, isError } = useTenantOidc();
  const updateOidc = useUpdateOidc();
  const { toast } = useToast();

  const [form, setForm] = useState<OidcFormState>(EMPTY_FORM);

  // Pre-fill form when config loads
  useEffect(() => {
    if (!oidcConfig) return;
    setForm({
      issuerUri: String(oidcConfig['issuerUri'] ?? ''),
      clientId: String(oidcConfig['clientId'] ?? ''),
      clientSecret: String(oidcConfig['clientSecret'] ?? ''),
      audience: String(oidcConfig['audience'] ?? ''),
      rolesClaim: String(oidcConfig['rolesClaim'] ?? ''),
    });
  }, [oidcConfig]);

  function handleChange(field: keyof OidcFormState, value: string) {
    setForm((prev) => ({ ...prev, [field]: value }));
  }

  async function handleSave(e: React.FormEvent) {
    e.preventDefault();
    try {
      await updateOidc.mutateAsync({
        issuerUri: form.issuerUri,
        clientId: form.clientId,
        clientSecret: form.clientSecret,
        audience: form.audience,
        rolesClaim: form.rolesClaim,
      });
      toast({ title: 'OIDC configuration saved', variant: 'success' });
    } catch (err) {
      toast({ title: 'Save failed', description: String(err), variant: 'error' });
    }
  }

  async function handleReset() {
    try {
      await updateOidc.mutateAsync({});
      setForm(EMPTY_FORM);
      toast({ title: 'Reset to Logto (default)', variant: 'success' });
    } catch (err) {
      toast({ title: 'Reset failed', description: String(err), variant: 'error' });
    }
  }

  if (isLoading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', padding: 64 }}>
        <Spinner />
      </div>
    );
  }

  if (isError) {
    return (
      <div style={{ padding: 24 }}>
        <Alert variant="error" title="Failed to load OIDC configuration">
          Could not fetch OIDC config. Please refresh.
        </Alert>
      </div>
    );
  }

  const hasExternalOidc = oidcConfig ? isExternalOidc(oidcConfig) : false;

  return (
    <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <h1 style={{ margin: 0, fontSize: '1.25rem', fontWeight: 600 }}>OIDC Configuration</h1>
        <Badge
          label={hasExternalOidc ? 'External OIDC configured' : 'Using Logto (default)'}
          color={hasExternalOidc ? 'primary' : 'auto'}
        />
      </div>

      <Card title="External OIDC Provider">
        <p className={styles.description} style={{ marginBottom: 16 }}>
          Configure an external OIDC provider for your team to sign in. Leave blank to use the
          default Logto-based authentication.
        </p>

        <form onSubmit={handleSave} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <FormField label="Issuer URI" htmlFor="oidc-issuer">
            <Input
              id="oidc-issuer"
              type="url"
              placeholder="https://your-idp.example.com/oidc"
              value={form.issuerUri}
              onChange={(e) => handleChange('issuerUri', e.target.value)}
            />
          </FormField>

          <FormField label="Client ID" htmlFor="oidc-client-id">
            <Input
              id="oidc-client-id"
              placeholder="your-client-id"
              value={form.clientId}
              onChange={(e) => handleChange('clientId', e.target.value)}
            />
          </FormField>

          <FormField label="Client Secret" htmlFor="oidc-client-secret">
            <Input
              id="oidc-client-secret"
              type="password"
              placeholder="••••••••"
              value={form.clientSecret}
              onChange={(e) => handleChange('clientSecret', e.target.value)}
            />
          </FormField>

          <FormField label="Audience" htmlFor="oidc-audience">
            <Input
              id="oidc-audience"
              placeholder="https://api.your-service.example.com"
              value={form.audience}
              onChange={(e) => handleChange('audience', e.target.value)}
            />
          </FormField>

          <FormField label="Roles Claim" htmlFor="oidc-roles-claim">
            <Input
              id="oidc-roles-claim"
              placeholder="roles"
              value={form.rolesClaim}
              onChange={(e) => handleChange('rolesClaim', e.target.value)}
            />
          </FormField>

          <div style={{ display: 'flex', gap: 8 }}>
            <Button type="submit" variant="primary" loading={updateOidc.isPending}>
              Save Configuration
            </Button>
            {hasExternalOidc && (
              <Button
                type="button"
                variant="secondary"
                onClick={handleReset}
                loading={updateOidc.isPending}
              >
                Reset to Logto
              </Button>
            )}
          </div>
        </form>
      </Card>
    </div>
  );
}
