import { useState } from 'react';
import {
  Alert, AlertDialog, Badge, Button, Card, DataTable,
  EmptyState, FormField, Input, Spinner, useToast,
} from '@cameleer/design-system';
import type { Column } from '@cameleer/design-system';
import { Shield, Plus, Trash2, FlaskConical } from 'lucide-react';
import {
  useSsoConnectors, useCreateSsoConnector, useDeleteSsoConnector, useTestSsoConnector,
} from '../../api/tenant-hooks';
import type { SsoConnector } from '../../types/api';

const PROVIDERS = [
  { value: 'OIDC', label: 'OIDC', type: 'oidc' },
  { value: 'SAML', label: 'SAML', type: 'saml' },
  { value: 'AzureAD', label: 'Azure AD (SAML)', type: 'saml' },
  { value: 'AzureAdOidc', label: 'Azure AD (OIDC)', type: 'oidc' },
  { value: 'GoogleWorkspace', label: 'Google Workspace', type: 'oidc' },
  { value: 'Okta', label: 'Okta', type: 'oidc' },
];

function providerType(name: string): 'oidc' | 'saml' {
  return PROVIDERS.find((p) => p.value === name)?.type as 'oidc' | 'saml' ?? 'oidc';
}

function providerLabel(name: string): string {
  return PROVIDERS.find((p) => p.value === name)?.label ?? name;
}

const selectStyle: React.CSSProperties = {
  width: '100%', padding: '6px 10px', borderRadius: 6,
  border: '1px solid var(--border)', background: 'var(--bg-surface)',
  color: 'var(--text-primary)', fontSize: '0.875rem',
};

export function SsoPage() {
  const { data: connectors, isLoading, isError } = useSsoConnectors();
  const createConnector = useCreateSsoConnector();
  const deleteConnector = useDeleteSsoConnector();
  const testConnector = useTestSsoConnector();
  const { toast } = useToast();

  const [showCreate, setShowCreate] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<SsoConnector | null>(null);

  // Create form state
  const [provider, setProvider] = useState('OIDC');
  const [connectorName, setConnectorName] = useState('');
  const [domains, setDomains] = useState('');
  // OIDC fields
  const [issuer, setIssuer] = useState('');
  const [clientId, setClientId] = useState('');
  const [clientSecret, setClientSecret] = useState('');
  // SAML fields
  const [metadataUrl, setMetadataUrl] = useState('');

  function resetForm() {
    setProvider('OIDC');
    setConnectorName('');
    setDomains('');
    setIssuer('');
    setClientId('');
    setClientSecret('');
    setMetadataUrl('');
    setShowCreate(false);
  }

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    const type = providerType(provider);
    const config: Record<string, unknown> = type === 'oidc'
      ? { clientId, clientSecret, issuer: issuer || undefined }
      : { metadataUrl };

    try {
      await createConnector.mutateAsync({
        providerName: provider,
        connectorName,
        config,
        domains: domains.split(',').map((d) => d.trim()).filter(Boolean),
      });
      toast({ title: `SSO connector "${connectorName}" created`, variant: 'success' });
      resetForm();
    } catch (err) {
      toast({ title: 'Failed to create connector', description: String(err), variant: 'error' });
    }
  }

  async function handleDelete() {
    if (!deleteTarget) return;
    try {
      await deleteConnector.mutateAsync(deleteTarget.id);
      toast({ title: `Deleted "${deleteTarget.connectorName}"`, variant: 'success' });
      setDeleteTarget(null);
    } catch (err) {
      toast({ title: 'Delete failed', description: String(err), variant: 'error' });
      setDeleteTarget(null);
    }
  }

  async function handleTest(connector: SsoConnector) {
    try {
      const result = await testConnector.mutateAsync(connector.id);
      if (result.status === 'ok') {
        toast({ title: 'Connection test passed', description: `${connector.connectorName} is reachable`, variant: 'success' });
      } else {
        toast({ title: 'Connection test failed', description: 'IdP metadata could not be resolved', variant: 'warning' });
      }
    } catch (err) {
      toast({ title: 'Connection test failed', description: String(err), variant: 'error' });
    }
  }

  const columns: Column<SsoConnector>[] = [
    {
      key: 'connectorName',
      header: 'Name',
      render: (_v, row) => row.connectorName,
    },
    {
      key: 'providerName',
      header: 'Provider',
      render: (_v, row) => <Badge label={providerLabel(row.providerName)} color="primary" />,
    },
    {
      key: 'domains',
      header: 'Domains',
      render: (_v, row) => (
        <span style={{ fontFamily: 'monospace', fontSize: '0.8125rem' }}>
          {row.domains?.join(', ') || '--'}
        </span>
      ),
    },
    {
      key: 'id',
      header: 'Actions',
      render: (_v, row) => (
        <div style={{ display: 'flex', gap: 4 }}>
          <Button
            variant="secondary"
            onClick={(e) => { e.stopPropagation(); handleTest(row); }}
            disabled={testConnector.isPending}
          >
            <FlaskConical size={14} style={{ marginRight: 4 }} />
            Test
          </Button>
          <Button
            variant="danger"
            onClick={(e) => { e.stopPropagation(); setDeleteTarget(row); }}
          >
            <Trash2 size={14} />
          </Button>
        </div>
      ),
    },
  ];

  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 SSO connectors">
          Could not fetch SSO configuration. Please refresh.
        </Alert>
      </div>
    );
  }

  const isOidc = providerType(provider) === 'oidc';

  return (
    <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h1 style={{ margin: 0, fontSize: '1.25rem', fontWeight: 600 }}>Enterprise SSO</h1>
        <Button variant="primary" onClick={() => setShowCreate((v) => !v)}>
          <Plus size={16} style={{ marginRight: 6 }} />
          Add SSO Connection
        </Button>
      </div>

      {showCreate && (
        <Card title="New SSO Connection">
          <form onSubmit={handleCreate} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <FormField label="Provider" htmlFor="sso-provider">
              <select id="sso-provider" value={provider} onChange={(e) => setProvider(e.target.value)} style={selectStyle}>
                {PROVIDERS.map((p) => (
                  <option key={p.value} value={p.value}>{p.label}</option>
                ))}
              </select>
            </FormField>

            <FormField label="Display Name" htmlFor="sso-name">
              <Input
                id="sso-name"
                placeholder="e.g. Acme Corp SSO"
                value={connectorName}
                onChange={(e) => setConnectorName(e.target.value)}
                required
              />
            </FormField>

            <FormField label="Email Domains" htmlFor="sso-domains" hint="Comma-separated domains for SSO routing (e.g. acme.com)">
              <Input
                id="sso-domains"
                placeholder="acme.com, acme.io"
                value={domains}
                onChange={(e) => setDomains(e.target.value)}
              />
            </FormField>

            {isOidc ? (
              <>
                {provider !== 'GoogleWorkspace' && (
                  <FormField label="Issuer URI" htmlFor="sso-issuer">
                    <Input
                      id="sso-issuer"
                      type="url"
                      placeholder="https://login.microsoftonline.com/{tenant}/v2.0"
                      value={issuer}
                      onChange={(e) => setIssuer(e.target.value)}
                      required
                    />
                  </FormField>
                )}
                <FormField label="Client ID" htmlFor="sso-client-id">
                  <Input
                    id="sso-client-id"
                    value={clientId}
                    onChange={(e) => setClientId(e.target.value)}
                    required
                  />
                </FormField>
                <FormField label="Client Secret" htmlFor="sso-client-secret">
                  <Input
                    id="sso-client-secret"
                    type="password"
                    value={clientSecret}
                    onChange={(e) => setClientSecret(e.target.value)}
                    required
                  />
                </FormField>
              </>
            ) : (
              <FormField label="SAML Metadata URL" htmlFor="sso-metadata">
                <Input
                  id="sso-metadata"
                  type="url"
                  placeholder="https://idp.acme.com/metadata.xml"
                  value={metadataUrl}
                  onChange={(e) => setMetadataUrl(e.target.value)}
                  required
                />
              </FormField>
            )}

            <div style={{ display: 'flex', gap: 8 }}>
              <Button type="submit" variant="primary" loading={createConnector.isPending}>
                Create
              </Button>
              <Button type="button" variant="secondary" onClick={resetForm}>
                Cancel
              </Button>
            </div>
          </form>
        </Card>
      )}

      {(!connectors || connectors.length === 0) && !showCreate && (
        <EmptyState
          icon={<Shield size={32} />}
          title="No SSO connections"
          description="Add an enterprise SSO connection to let your team sign in with their corporate identity provider."
          action={
            <Button variant="primary" onClick={() => setShowCreate(true)}>
              <Plus size={16} style={{ marginRight: 6 }} />
              Add SSO Connection
            </Button>
          }
        />
      )}

      {connectors && connectors.length > 0 && (
        <DataTable columns={columns} data={connectors} />
      )}

      <AlertDialog
        open={deleteTarget !== null}
        onClose={() => setDeleteTarget(null)}
        onConfirm={handleDelete}
        title="Delete SSO Connection"
        description={`Are you sure you want to delete "${deleteTarget?.connectorName ?? ''}"? Users authenticating via this provider will lose access.`}
        confirmLabel="Delete"
        cancelLabel="Cancel"
        variant="danger"
        loading={deleteConnector.isPending}
      />
    </div>
  );
}
