'use client';

import { LayoutShell } from '../../../../components/layout-shell';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import api from '../../../../lib/api-client';
import { useState } from 'react';
import { Modal } from '../../../../components/ui/modal';
import { Check, Copy, Download, FileText, KeyRound, Plus, Trash2 } from 'lucide-react';

const SCOPE_OPTIONS = [
  {
    value: 'field_reports.read',
    label: 'Field reports',
    description: 'Read deliveries, anonymous reports, issue reports and their evidence.',
  },
  {
    value: 'supplier_insights',
    label: 'Supplier insights',
    description: 'Read supplier insight endpoints.',
  },
  {
    value: 'purchase_orders',
    label: 'Purchase orders',
    description: 'Use approved purchase-order integration endpoints.',
  },
];

export default function ApiManagementPage() {
  const queryClient = useQueryClient();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [newKeyName, setNewKeyName] = useState('');
  const [selectedScopes, setSelectedScopes] = useState<string[]>(['field_reports.read']);
  const [generatedKey, setGeneratedKey] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);

  const { data: keys, isLoading } = useQuery({
    queryKey: ['api-keys'],
    queryFn: async () => (await api.get('/api-keys')).data.data,
  });

  const createMutation = useMutation({
    mutationFn: async () => (
      await api.post('/api-keys', { name: newKeyName, scopes: selectedScopes })
    ).data,
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['api-keys'] });
      setGeneratedKey(data.api_key);
    },
  });

  const revokeMutation = useMutation({
    mutationFn: async (id: number) => api.delete('/api-keys/' + id),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['api-keys'] }),
  });

  const closeModal = () => {
    setIsModalOpen(false);
    setGeneratedKey(null);
    setCopied(false);
    setNewKeyName('');
    setSelectedScopes(['field_reports.read']);
    createMutation.reset();
  };

  const toggleScope = (scope: string) => {
    setSelectedScopes(current => (
      current.includes(scope) ? current.filter(item => item !== scope) : [...current, scope]
    ));
  };

  const copyKey = async () => {
    if (!generatedKey) return;
    await navigator.clipboard.writeText(generatedKey);
    setCopied(true);
  };

  return (
    <LayoutShell role="SUPER_ADMIN">
      <div className="space-y-6">
        <div className="flex flex-col gap-4 border-b border-slate-200 pb-5 sm:flex-row sm:items-end sm:justify-between">
          <div>
            <h1 className="text-2xl font-bold text-slate-900">API Management</h1>
            <p className="mt-1 text-sm text-slate-500">Issue narrowly scoped credentials for trusted integrations.</p>
          </div>
          <div className="flex flex-wrap gap-2">
            <a href="/docs/field-reports-openapi.json" download title="Download OpenAPI specification" aria-label="Download OpenAPI specification" className="rounded-md border border-slate-300 bg-white p-2.5 text-slate-700 hover:bg-slate-50">
              <Download className="h-4 w-4" />
            </a>
            <a
              href="/docs/field-reports-api.md"
              target="_blank"
              rel="noreferrer"
              className="inline-flex items-center gap-2 rounded-md border border-slate-300 bg-white px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
            >
              <FileText className="h-4 w-4" />
              API Guide
            </a>
            <button
              onClick={() => setIsModalOpen(true)}
              className="inline-flex items-center gap-2 rounded-md bg-brand px-3 py-2 text-sm font-semibold text-white hover:bg-emerald-700"
            >
              <Plus className="h-4 w-4" />
              Generate Key
            </button>
          </div>
        </div>

        <section className="overflow-hidden rounded-lg border border-slate-200 bg-white">
          <div className="border-b border-slate-200 px-5 py-4">
            <h2 className="font-semibold text-slate-900">Integration Keys</h2>
          </div>
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-slate-200 text-sm">
              <thead className="bg-slate-50 text-left text-xs font-semibold uppercase text-slate-500">
                <tr>
                  <th className="px-5 py-3">Name</th>
                  <th className="px-5 py-3">Scopes</th>
                  <th className="px-5 py-3">Last used</th>
                  <th className="px-5 py-3">Status</th>
                  <th className="w-16 px-5 py-3"><span className="sr-only">Actions</span></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {isLoading && (
                  <tr><td colSpan={5} className="px-5 py-10 text-center text-slate-500">Loading keys...</td></tr>
                )}
                {!isLoading && keys?.length === 0 && (
                  <tr><td colSpan={5} className="px-5 py-10 text-center text-slate-500">No API keys have been generated.</td></tr>
                )}
                {keys?.map((key: any) => (
                  <tr key={key.id}>
                    <td className="px-5 py-4 font-medium text-slate-900">{key.name}</td>
                    <td className="px-5 py-4">
                      <div className="flex flex-wrap gap-1.5">
                        {(key.scopes || []).map((scope: string) => (
                          <span key={scope} className="rounded bg-slate-100 px-2 py-1 font-mono text-xs text-slate-600">
                            {scope}
                          </span>
                        ))}
                      </div>
                    </td>
                    <td className="px-5 py-4 text-slate-500">
                      {key.last_used_at ? new Date(key.last_used_at).toLocaleString() : 'Never'}
                    </td>
                    <td className="px-5 py-4">
                      <span className={key.status === 'active'
                        ? 'text-sm font-semibold text-emerald-700'
                        : 'text-sm font-semibold text-slate-400'}
                      >
                        {key.status === 'active' ? 'Active' : 'Revoked'}
                      </span>
                    </td>
                    <td className="px-5 py-4 text-right">
                      {key.status === 'active' && (
                        <button
                          onClick={() => revokeMutation.mutate(key.id)}
                          disabled={revokeMutation.isPending}
                          title="Revoke API key"
                          aria-label={'Revoke ' + key.name}
                          className="rounded-md p-2 text-slate-400 hover:bg-rose-50 hover:text-rose-600 disabled:opacity-50"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </section>
      </div>

      <Modal isOpen={isModalOpen} onClose={closeModal} title="Generate API Key">
        {!generatedKey ? (
          <div className="space-y-5">
            <div>
              <label htmlFor="api-key-name" className="block text-sm font-medium text-slate-700">Integration name</label>
              <input
                id="api-key-name"
                type="text"
                placeholder="e.g. Operations data warehouse"
                value={newKeyName}
                onChange={event => setNewKeyName(event.target.value)}
                className="mt-1.5 block w-full rounded-md border border-slate-300 px-3 py-2.5 text-sm focus:border-brand focus:outline-none focus:ring-2 focus:ring-brand/20"
              />
            </div>

            <fieldset>
              <legend className="text-sm font-medium text-slate-700">Access scopes</legend>
              <div className="mt-2 divide-y divide-slate-100 rounded-md border border-slate-200">
                {SCOPE_OPTIONS.map(scope => (
                  <label key={scope.value} className="flex cursor-pointer gap-3 px-3 py-3 hover:bg-slate-50">
                    <input
                      type="checkbox"
                      checked={selectedScopes.includes(scope.value)}
                      onChange={() => toggleScope(scope.value)}
                      className="mt-0.5 h-4 w-4 rounded border-slate-300 text-brand focus:ring-brand"
                    />
                    <span>
                      <span className="block text-sm font-semibold text-slate-800">{scope.label}</span>
                      <span className="block text-xs leading-5 text-slate-500">{scope.description}</span>
                    </span>
                  </label>
                ))}
              </div>
            </fieldset>

            {createMutation.isError && (
              <p className="text-sm text-rose-600">The key could not be generated. Check the selected scopes and try again.</p>
            )}

            <div className="flex justify-end gap-2 border-t border-slate-100 pt-4">
              <button onClick={closeModal} className="rounded-md px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-100">
                Cancel
              </button>
              <button
                onClick={() => createMutation.mutate()}
                disabled={!newKeyName.trim() || selectedScopes.length === 0 || createMutation.isPending}
                className="inline-flex items-center gap-2 rounded-md bg-brand px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-700 disabled:opacity-50"
              >
                <KeyRound className="h-4 w-4" />
                {createMutation.isPending ? 'Generating...' : 'Generate'}
              </button>
            </div>
          </div>
        ) : (
          <div className="space-y-4">
            <div className="rounded-md border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900">
              This key is displayed once. Store it in the receiving system's secret manager before closing.
            </div>
            <div className="flex items-start gap-2 rounded-md border border-slate-300 bg-slate-50 p-3">
              <code className="min-w-0 flex-1 break-all text-xs leading-5 text-slate-800">{generatedKey}</code>
              <button
                onClick={copyKey}
                title="Copy API key"
                aria-label="Copy API key"
                className="shrink-0 rounded-md p-2 text-slate-600 hover:bg-white"
              >
                {copied ? <Check className="h-4 w-4 text-emerald-600" /> : <Copy className="h-4 w-4" />}
              </button>
            </div>
            <button onClick={closeModal} className="w-full rounded-md bg-brand px-4 py-2.5 text-sm font-semibold text-white hover:bg-emerald-700">
              Done
            </button>
          </div>
        )}
      </Modal>
    </LayoutShell>
  );
}
