import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect, useRef, useState } from 'react';
import { useParams } from 'react-router-dom';

import { WorkspacesService } from '@/client/services/WorkspacesService';
import { Toggle } from '@/components/settings/primitives';

// ---------------------------------------------------------------------------
// WorkspaceSettingsPage
// ---------------------------------------------------------------------------

export function WorkspaceSettingsPage() {
  const { workspaceName } = useParams<{ workspaceName: string }>();
  const queryClient = useQueryClient();

  const {
    data: settings,
    isLoading,
    error,
  } = useQuery({
    queryKey: ['workspace', workspaceName, 'settings'],
    queryFn: () => {
      if (!workspaceName) throw new Error('No workspace name');
      return WorkspacesService.workspaceGetSettings({ workspaceName }).then((r) => r.data);
    },
    enabled: !!workspaceName,
    staleTime: 1000 * 60 * 2,
  });

  const [form, setForm] = useState({
    default_branch_name: 'main',
    default_repo_visibility: 'private',
    allow_member_invites: true,
    allow_public_repos: true,
    require_two_factor: false,
    issue_tracking_enabled: true,
    pull_requests_enabled: true,
    wiki_enabled: true,
  });
  const [saved, setSaved] = useState(false);

  const updateMutation = useMutation({
    mutationFn: () => {
      if (!workspaceName) throw new Error('No workspace name');
      return WorkspacesService.workspaceUpdateSettings({
        workspaceName,
        requestBody: {
          default_branch_name: form.default_branch_name,
          default_repo_visibility: form.default_repo_visibility,
          allow_member_invites: form.allow_member_invites,
          allow_public_repos: form.allow_public_repos,
          require_two_factor: form.require_two_factor,
          issue_tracking_enabled: form.issue_tracking_enabled,
          pull_requests_enabled: form.pull_requests_enabled,
          wiki_enabled: form.wiki_enabled,
        },
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['workspace', workspaceName, 'settings'] });
      setSaved(true);
      setTimeout(() => setSaved(false), 2500);
    },
  });

  const initialized = useRef(false);
  useEffect(() => {
    if (settings && !initialized.current) {
      initialized.current = true;
      setForm({
        default_branch_name: settings.default_branch_name,
        default_repo_visibility: settings.default_repo_visibility,
        allow_member_invites: settings.allow_member_invites,
        allow_public_repos: settings.allow_public_repos,
        require_two_factor: settings.require_two_factor,
        issue_tracking_enabled: settings.issue_tracking_enabled,
        pull_requests_enabled: settings.pull_requests_enabled,
        wiki_enabled: settings.wiki_enabled,
      });
    }
  }, [settings]);

  if (isLoading) {
    return (
      <div className="flex items-center gap-2 p-8 text-[14px] text-muted-foreground">
        <span className="inline-block size-4 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
        Loading settings…
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-8">
        <div className="rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-[14px] text-destructive">
          Failed to load workspace settings.
        </div>
      </div>
    );
  }

  return (
    <div className="px-6 pt-8 pb-16">
      <div className="mb-6">
        <h1 className="text-xl font-semibold text-foreground">Settings</h1>
        <p className="mt-1 text-[13px] text-muted-foreground">
          Configure workspace-wide defaults and policies.
        </p>
      </div>

      <div className="max-w-[520px] space-y-6">
        {/* Defaults section */}
        <section>
          <h2 className="mb-4 text-[14px] font-semibold text-foreground">Repository defaults</h2>

          <div className="space-y-4">
            <div>
              <label
                htmlFor="ws-default-branch"
                className="mb-1.5 block text-[13px] font-semibold text-foreground"
              >
                Default branch name
              </label>
              <input
                id="ws-default-branch"
                type="text"
                value={form.default_branch_name}
                onChange={(e) => setForm((f) => ({ ...f, default_branch_name: e.target.value }))}
                className="w-full rounded-md border border-border bg-card px-3 py-[7px] text-[14px] text-foreground outline-none transition-shadow focus:shadow-[inset_0_0_0_2px_var(--ring)] focus:border-transparent"
              />
            </div>

            <div>
              <label
                htmlFor="ws-default-vis"
                className="mb-1.5 block text-[13px] font-semibold text-foreground"
              >
                Default repository visibility
              </label>
              <select
                id="ws-default-vis"
                value={form.default_repo_visibility}
                onChange={(e) =>
                  setForm((f) => ({ ...f, default_repo_visibility: e.target.value }))
                }
                className="w-full rounded-md border border-border bg-card px-3 py-[7px] text-[14px] text-foreground outline-none transition-shadow focus:shadow-[inset_0_0_0_2px_var(--ring)] focus:border-transparent"
              >
                <option value="private">Private</option>
                <option value="internal">Internal</option>
                <option value="public">Public</option>
              </select>
            </div>
          </div>
        </section>

        {/* Policies section */}
        <section>
          <h2 className="mb-4 text-[14px] font-semibold text-foreground">Policies</h2>
          <div className="space-y-1 divide-y divide-border">
            <Toggle
              label="Allow members to invite others"
              description="Members can invite new people to the workspace."
              checked={form.allow_member_invites}
              onChange={(v) => setForm((f) => ({ ...f, allow_member_invites: v }))}
            />
            <Toggle
              label="Allow public repositories"
              description="Workspace members can create public repositories."
              checked={form.allow_public_repos}
              onChange={(v) => setForm((f) => ({ ...f, allow_public_repos: v }))}
            />
            <Toggle
              label="Require two-factor authentication"
              description="All members must have 2FA enabled."
              checked={form.require_two_factor}
              onChange={(v) => setForm((f) => ({ ...f, require_two_factor: v }))}
            />
          </div>
        </section>

        {/* Features section */}
        <section>
          <h2 className="mb-4 text-[14px] font-semibold text-foreground">Features</h2>
          <div className="space-y-1 divide-y divide-border">
            <Toggle
              label="Issue tracking"
              description="Enable the issue tracker for this workspace."
              checked={form.issue_tracking_enabled}
              onChange={(v) => setForm((f) => ({ ...f, issue_tracking_enabled: v }))}
            />
            <Toggle
              label="Pull requests"
              description="Enable pull request workflow for this workspace."
              checked={form.pull_requests_enabled}
              onChange={(v) => setForm((f) => ({ ...f, pull_requests_enabled: v }))}
            />
            <Toggle
              label="Wiki"
              description="Enable the wiki for documentation."
              checked={form.wiki_enabled}
              onChange={(v) => setForm((f) => ({ ...f, wiki_enabled: v }))}
            />
          </div>
        </section>

        {/* Save bar */}
        <div className="flex items-center gap-3 border-t border-border pt-4">
          <button
            type="button"
            onClick={() => updateMutation.mutate()}
            disabled={updateMutation.isPending}
            className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-[5px] text-[13px] font-medium text-primary-foreground transition-colors hover:bg-primary/85 disabled:opacity-60"
          >
            {updateMutation.isPending && (
              <span className="inline-block size-3.5 animate-spin rounded-full border-2 border-primary-foreground/40 border-t-primary-foreground" />
            )}
            {updateMutation.isPending ? 'Saving…' : 'Save settings'}
          </button>

          {saved && <span className="text-[13px] text-primary">✓ Saved</span>}

          {updateMutation.error && (
            <span className="text-[13px] text-destructive">
              {(updateMutation.error as Error)?.message ?? 'Save failed'}
            </span>
          )}
        </div>
      </div>
    </div>
  );
}
