'use client';

import { useCallback, useEffect, useState } from 'react';
import { Copy, KeyRound, Loader2, LockKeyhole, Plus, RefreshCw } from 'lucide-react';
import { AdminShell } from '@/components/id/admin-shell';
import { useAuth } from '@/components/id/auth-provider';
import { useToast } from '@/components/id/toast-provider';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { OAuthClient, OAuthScope, apiFetch } from '@/lib/api';

export default function AdminOAuthPage() {
  const { token } = useAuth();
  const { showToast } = useToast();
  const [clients, setClients] = useState<OAuthClient[]>([]);
  const [scopes, setScopes] = useState<OAuthScope[]>([]);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [secretDialog, setSecretDialog] = useState<{ clientId: string; clientSecret: string } | null>(null);
  const [form, setForm] = useState({ name: '', redirectUris: '', type: 'CONFIDENTIAL', selectedScopes: ['openid', 'profile', 'email'] as string[] });

  const loadData = useCallback(async () => {
    if (!token) return;
    setLoading(true);
    try {
      const [clientsResponse, scopesResponse] = await Promise.all([
        apiFetch<{ clients: OAuthClient[] }>('/admin/rbac/oauth-clients', {}, token),
        apiFetch<{ scopes: OAuthScope[] }>('/admin/rbac/oauth-scopes', {}, token)
      ]);
      setClients(clientsResponse.clients ?? []);
      setScopes(scopesResponse.scopes ?? []);
    } catch (error) {
      showToast(error instanceof Error ? error.message : 'Не удалось загрузить OAuth-приложения');
    } finally {
      setLoading(false);
    }
  }, [showToast, token]);

  useEffect(() => {
    void loadData();
  }, [loadData]);

  async function handleCreate() {
    if (!token) return;
    const redirectUris = form.redirectUris
      .split('\n')
      .map((item) => item.trim())
      .filter(Boolean);
    if (!form.name.trim() || !redirectUris.length || !form.selectedScopes.length) {
      showToast('Заполните название, redirect URI и scopes');
      return;
    }

    setCreating(true);
    try {
      const created = await apiFetch<OAuthClient>('/admin/rbac/oauth-clients', {
        method: 'POST',
        body: JSON.stringify({
          name: form.name.trim(),
          redirectUris,
          scopes: form.selectedScopes,
          type: form.type
        })
      }, token);
      showToast('OAuth-приложение создано');
      setDialogOpen(false);
      setForm({ name: '', redirectUris: '', type: 'CONFIDENTIAL', selectedScopes: ['openid', 'profile', 'email'] });
      if (created.clientSecret) {
        setSecretDialog({ clientId: created.clientId, clientSecret: created.clientSecret });
      }
      await loadData();
    } catch (error) {
      showToast(error instanceof Error ? error.message : 'Не удалось создать приложение');
    } finally {
      setCreating(false);
    }
  }

  async function handleRotateSecret(clientId: string) {
    if (!token) return;
    try {
      const response = await apiFetch<{ clientId: string; clientSecret: string }>(`/admin/rbac/oauth-clients/${clientId}/rotate-secret`, { method: 'POST' }, token);
      setSecretDialog(response);
      showToast('Новый client secret сгенерирован');
    } catch (error) {
      showToast(error instanceof Error ? error.message : 'Не удалось перевыпустить secret');
    }
  }

  async function handleToggleActive(client: OAuthClient) {
    if (!token) return;
    try {
      await apiFetch(`/admin/rbac/oauth-clients/${client.clientId}`, {
        method: 'PATCH',
        body: JSON.stringify({ isActive: !client.isActive })
      }, token);
      showToast(client.isActive ? 'Приложение отключено' : 'Приложение включено');
      await loadData();
    } catch (error) {
      showToast(error instanceof Error ? error.message : 'Не удалось обновить приложение');
    }
  }

  function copyText(value: string, label: string) {
    void navigator.clipboard.writeText(value);
    showToast(`${label} скопирован`);
  }

  return (
    <AdminShell active="/admin/oauth">
      <div className="mb-6 flex items-center justify-between gap-4">
        <div>
          <h2 className="text-2xl font-medium">OAuth-приложения</h2>
          <p className="text-sm text-[#667085]">Создание клиентов как на oauth.yandex.ru: client_id, secret, redirect URI и scopes</p>
        </div>
        <Button onClick={() => setDialogOpen(true)}>
          <Plus className="h-4 w-4" />
          Новое приложение
        </Button>
      </div>

      {loading ? (
        <div className="flex items-center justify-center gap-2 py-16 text-[#667085]">
          <Loader2 className="h-5 w-5 animate-spin" />
          Загрузка...
        </div>
      ) : (
        <div className="grid gap-4 md:grid-cols-2">
          {clients.map((client) => (
            <Card key={client.id} className={client.isActive ? '' : 'opacity-70'}>
              <CardHeader>
                <LockKeyhole className="h-6 w-6" />
                <CardTitle>{client.name}</CardTitle>
                <CardDescription>{client.type === 'PUBLIC' ? 'Публичное приложение' : 'Confidential приложение'}</CardDescription>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="rounded-2xl bg-[#f4f5f8] p-4 text-sm">
                  <div className="mb-2 flex items-center justify-between gap-2">
                    <span className="font-medium">Client ID</span>
                    <Button variant="ghost" size="icon" aria-label="Скопировать client id" onClick={() => copyText(client.clientId, 'Client ID')}>
                      <Copy className="h-4 w-4" />
                    </Button>
                  </div>
                  <code className="break-all text-xs">{client.clientId}</code>
                </div>
                <div className="rounded-2xl bg-[#f4f5f8] p-4 text-sm">
                  <div className="mb-2 font-medium">Redirect URI</div>
                  {client.redirectUris.map((uri) => (
                    <div key={uri} className="break-all text-xs text-[#667085]">
                      {uri}
                    </div>
                  ))}
                </div>
                <div className="rounded-2xl bg-[#f4f5f8] p-4 text-sm">
                  <div className="mb-2 flex items-center gap-2 font-medium">
                    <KeyRound className="h-4 w-4" />
                    Scopes
                  </div>
                  <p>{client.scopes.join(', ')}</p>
                </div>
                <div className="flex flex-wrap gap-2">
                  {client.type !== 'PUBLIC' ? (
                    <Button variant="secondary" size="sm" onClick={() => void handleRotateSecret(client.clientId)}>
                      <RefreshCw className="h-4 w-4" />
                      Новый secret
                    </Button>
                  ) : null}
                  <Button variant="secondary" size="sm" onClick={() => void handleToggleActive(client)}>
                    {client.isActive ? 'Отключить' : 'Включить'}
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
          {!clients.length ? <p className="text-[#667085]">OAuth-приложения ещё не созданы</p> : null}
        </div>
      )}

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Новое OAuth-приложение</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <label className="mb-2 block text-sm font-medium">Название</label>
              <Input value={form.name} onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))} placeholder="Lendry Docs" />
            </div>
            <div>
              <label className="mb-2 block text-sm font-medium">Тип клиента</label>
              <select
                value={form.type}
                onChange={(event) => setForm((current) => ({ ...current, type: event.target.value }))}
                className="h-11 w-full rounded-xl border border-[#eceef4] bg-white px-3 text-sm"
              >
                <option value="CONFIDENTIAL">Confidential (с client secret)</option>
                <option value="PUBLIC">Public (без secret)</option>
              </select>
            </div>
            <div>
              <label className="mb-2 block text-sm font-medium">Redirect URI (по одному на строку)</label>
              <textarea
                value={form.redirectUris}
                onChange={(event) => setForm((current) => ({ ...current, redirectUris: event.target.value }))}
                placeholder="https://app.example.com/oauth/callback"
                className="min-h-[96px] w-full rounded-xl border border-[#eceef4] bg-white px-3 py-2 text-sm"
              />
            </div>
            <div>
              <label className="mb-2 block text-sm font-medium">Scopes</label>
              <div className="space-y-2">
                {scopes.map((scope) => (
                  <label key={scope.id} className="flex items-center gap-2 rounded-xl bg-[#f4f5f8] px-3 py-2 text-sm">
                    <input
                      type="checkbox"
                      checked={form.selectedScopes.includes(scope.slug)}
                      onChange={(event) =>
                        setForm((current) => ({
                          ...current,
                          selectedScopes: event.target.checked
                            ? [...current.selectedScopes, scope.slug]
                            : current.selectedScopes.filter((item) => item !== scope.slug)
                        }))
                      }
                    />
                    <span className="font-medium">{scope.name}</span>
                    <span className="text-[#667085]">({scope.slug})</span>
                  </label>
                ))}
              </div>
            </div>
            <Button className="w-full" disabled={creating} onClick={() => void handleCreate()}>
              {creating ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Создать приложение'}
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      <Dialog open={Boolean(secretDialog)} onOpenChange={(open) => !open && setSecretDialog(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Client Secret</DialogTitle>
          </DialogHeader>
          <p className="text-sm text-[#667085]">Сохраните secret сейчас — он больше не будет показан полностью.</p>
          <div className="rounded-2xl bg-[#f4f5f8] p-4">
            <p className="mb-1 text-xs text-[#667085]">Client ID</p>
            <code className="break-all text-sm">{secretDialog?.clientId}</code>
            <p className="mb-1 mt-4 text-xs text-[#667085]">Client Secret</p>
            <code className="break-all text-sm">{secretDialog?.clientSecret}</code>
          </div>
          <Button className="w-full" onClick={() => secretDialog && copyText(secretDialog.clientSecret, 'Client Secret')}>
            <Copy className="h-4 w-4" />
            Скопировать secret
          </Button>
        </DialogContent>
      </Dialog>
    </AdminShell>
  );
}
