import { useState, useEffect } from 'react';
import { toast } from 'sonner';
import { ChevronDown } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@/components/ui/collapsible';
import { useClient } from 'hooks/useClient';

type GoogleOAuthSettings = {
  clientId: string;
  clientSecret: string;
};

const SCOPES = [
  { scope: 'gmail.readonly', description: 'Read emails' },
  { scope: 'calendar.readonly', description: 'Read calendar events' },
];

const SetupGuide = ({ redirectUri }: { redirectUri: string }) => {
  const [open, setOpen] = useState(false);

  return (
    <Collapsible open={open} onOpenChange={setOpen}>
      <CollapsibleTrigger className="flex items-center gap-2 text-sm font-medium text-duck-teal cursor-pointer hover:underline w-full">
        <ChevronDown className={`h-3.5 w-3.5 transition-transform duration-200 ${open ? 'rotate-180' : ''}`} />
        Step-by-step setup guide
      </CollapsibleTrigger>
      <CollapsibleContent>
        <ol className="mt-3 grid gap-4 text-sm text-duck-dark/70 dark:text-foreground/70 list-decimal list-outside pl-5">
          <li>
            <strong className="text-duck-dark dark:text-foreground">Create a Google Cloud project</strong>
            <p className="mt-1">
              Go to the{' '}
              <a
                href="https://console.cloud.google.com/projectcreate"
                target="_blank"
                rel="noopener noreferrer"
                className="text-duck-teal underline"
              >
                New Project
              </a>{' '}
              page. Give it a name (e.g. &quot;Officer&quot;) and click <strong>Create</strong>.
            </p>
          </li>

          <li>
            <strong className="text-duck-dark dark:text-foreground">Enable the APIs</strong>
            <p className="mt-1">
              Go to{' '}
              <a
                href="https://console.cloud.google.com/apis/library"
                target="_blank"
                rel="noopener noreferrer"
                className="text-duck-teal underline"
              >
                API Library
              </a>
              . Search for and enable each of these:
            </p>
            <ul className="mt-1 list-disc list-outside pl-5 grid gap-0.5">
              <li>
                <strong>Gmail API</strong>
              </li>
              <li>
                <strong>Google Calendar API</strong>
              </li>
            </ul>
            <p className="mt-1">
              Click each one, then click <strong>Enable</strong>.
            </p>
          </li>

          <li>
            <strong className="text-duck-dark dark:text-foreground">Configure the OAuth consent screen</strong>
            <p className="mt-1">
              Go to{' '}
              <a
                href="https://console.cloud.google.com/auth/branding"
                target="_blank"
                rel="noopener noreferrer"
                className="text-duck-teal underline"
              >
                OAuth Branding
              </a>
              .
            </p>
            <ul className="mt-1 list-disc list-outside pl-5 grid gap-0.5">
              <li>
                Set <strong>App name</strong> to your organization name or &quot;Officer&quot;
              </li>
              <li>
                Set <strong>User support email</strong> to your admin email
              </li>
              <li>
                Add your admin email under <strong>Developer contact information</strong>
              </li>
              <li>
                Click <strong>Save</strong>
              </li>
            </ul>
          </li>

          <li>
            <strong className="text-duck-dark dark:text-foreground">Set the audience</strong>
            <p className="mt-1">
              Go to{' '}
              <a
                href="https://console.cloud.google.com/auth/audience"
                target="_blank"
                rel="noopener noreferrer"
                className="text-duck-teal underline"
              >
                OAuth Audience
              </a>
              .
            </p>
            <ul className="mt-1 list-disc list-outside pl-5 grid gap-0.5">
              <li>
                If your team uses Google Workspace, select <strong>Internal</strong> — no verification needed
              </li>
              <li>
                Otherwise, select <strong>External</strong> and add your team's emails under <strong>Test users</strong>{' '}
                (required while the app is unverified; limit of 100 test users)
              </li>
            </ul>
          </li>

          <li>
            <strong className="text-duck-dark dark:text-foreground">Add scopes</strong>
            <p className="mt-1">
              In the left sidebar, click{' '}
              <a
                href="https://console.cloud.google.com/auth/scopes"
                target="_blank"
                rel="noopener noreferrer"
                className="text-duck-teal underline"
              >
                Data Access
              </a>
              , then click <strong>Add or remove scopes</strong>. Search for and add:
            </p>
            <ul className="mt-1 list-disc list-outside pl-5 grid gap-0.5">
              {SCOPES.map((s) => (
                <li key={s.scope}>
                  <code className="text-xs bg-duck-dark/5 dark:bg-foreground/5 px-1.5 py-0.5 rounded">{s.scope}</code> —{' '}
                  {s.description}
                </li>
              ))}
            </ul>
            <p className="mt-1">
              Click <strong>Update</strong>, then <strong>Save</strong>.
            </p>
            <p className="mt-2 text-xs text-duck-dark/50 dark:text-foreground/50">
              Note: <code className="bg-duck-dark/5 dark:bg-foreground/5 px-1 py-0.5 rounded">calendar.readonly</code>{' '}
              is classified as <strong>sensitive</strong> and{' '}
              <code className="bg-duck-dark/5 dark:bg-foreground/5 px-1 py-0.5 rounded">gmail.readonly</code> as{' '}
              <strong>restricted</strong> by Google. This is fine for Internal apps (Google Workspace) and External apps
              in testing mode. Publishing to production with restricted scopes requires Google verification.
            </p>
          </li>

          <li>
            <strong className="text-duck-dark dark:text-foreground">Create OAuth credentials</strong>
            <p className="mt-1">
              In the left sidebar, click{' '}
              <a
                href="https://console.cloud.google.com/auth/clients"
                target="_blank"
                rel="noopener noreferrer"
                className="text-duck-teal underline"
              >
                Clients
              </a>
              , then click <strong>Create OAuth client</strong>.
            </p>
            <ul className="mt-1 list-disc list-outside pl-5 grid gap-0.5">
              <li>
                Application type: <strong>Web application</strong>
              </li>
              <li>Name: anything (e.g. &quot;Officer&quot;)</li>
              <li>
                Authorized redirect URIs: add{' '}
                <code className="text-xs bg-duck-dark/5 dark:bg-foreground/5 px-1.5 py-0.5 rounded break-all">
                  {redirectUri}
                </code>
              </li>
              <li>
                Click <strong>Create</strong>
              </li>
            </ul>
          </li>

          <li>
            <strong className="text-duck-dark dark:text-foreground">Copy the credentials</strong>
            <p className="mt-1">
              A dialog will show your <strong>Client ID</strong> and <strong>Client Secret</strong>. Copy both and paste
              them into the fields below.
            </p>
          </li>
        </ol>
      </CollapsibleContent>
    </Collapsible>
  );
};

type VerifyStatus = { valid: boolean; error: string | null } | null;

const CredentialStatus = ({ status, isVerifying }: { status: VerifyStatus; isVerifying: boolean }) => {
  if (isVerifying) {
    return (
      <div className="flex items-center gap-2 rounded-lg border border-duck-dark/10 dark:border-foreground/10 p-3">
        <div className="h-2.5 w-2.5 rounded-full bg-duck-dark/20 dark:bg-foreground/20 animate-pulse shrink-0" />
        <span className="text-sm text-duck-dark/50 dark:text-foreground/50">Verifying credentials...</span>
      </div>
    );
  }

  if (!status) return null;

  return (
    <div className="flex items-center gap-2 rounded-lg border border-duck-dark/10 dark:border-foreground/10 p-3">
      <div className={`h-2.5 w-2.5 rounded-full shrink-0 ${status.valid ? 'bg-green-500' : 'bg-red-500'}`} />
      <span className={`text-sm ${status.valid ? 'text-duck-dark dark:text-foreground' : 'text-red-500'}`}>
        {status.valid ? 'Credentials valid' : (status.error ?? 'Invalid credentials')}
      </span>
    </div>
  );
};

export const GoogleOAuthConfig = () => {
  const client = useClient();
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [clientId, setClientId] = useState('');
  const [clientSecret, setClientSecret] = useState('');
  const [verifyStatus, setVerifyStatus] = useState<VerifyStatus>(null);
  const [isVerifying, setIsVerifying] = useState(false);

  const verify = () => {
    setIsVerifying(true);
    client
      .get<{ valid: boolean; error: string | null }>('/integrations/google/verify')
      .then(setVerifyStatus)
      .catch(() => setVerifyStatus({ valid: false, error: 'Verification request failed' }))
      .finally(() => setIsVerifying(false));
  };

  useEffect(() => {
    client
      .get<GoogleOAuthSettings | null>('/integrations/google/config')
      .then((data) => {
        if (data) {
          setClientId(data.clientId);
          setClientSecret(data.clientSecret);
        }
      })
      .catch(() => {})
      .finally(() => {
        setIsLoading(false);
      });
  }, []);

  // Verify on load if credentials exist
  useEffect(() => {
    if (!isLoading && clientId && clientSecret) verify();
  }, [isLoading]);

  const handleSave = async () => {
    if (isSaving) return;
    setIsSaving(true);
    try {
      await client.put('/integrations/google/config', { clientId: clientId.trim(), clientSecret: clientSecret.trim() });
      toast.success('Google OAuth configuration saved');
      verify();
    } catch {
      toast.error('Failed to save Google OAuth configuration');
    } finally {
      setIsSaving(false);
    }
  };

  if (isLoading) return null;

  const redirectUri = `${window.location.origin}/api/integrations/google/callback`;

  return (
    <div className="grid gap-5">
      <CredentialStatus status={verifyStatus} isVerifying={isVerifying} />

      <SetupGuide redirectUri={redirectUri} />

      <div className="border-t border-duck-dark/10 dark:border-foreground/10 pt-5 grid gap-5">
        <Label className="grid gap-2">
          <span className="text-duck-dark/70 dark:text-foreground/70">Client ID</span>
          <Input
            className="h-11 bg-background/60 border-duck-dark/20 text-duck-dark placeholder:text-duck-dark/40"
            type="text"
            value={clientId}
            onChange={(ev) => setClientId(ev.target.value)}
            placeholder="123456789.apps.googleusercontent.com"
          />
        </Label>

        <Label className="grid gap-2">
          <span className="text-duck-dark/70 dark:text-foreground/70">Client Secret</span>
          <Input
            className="h-11 bg-background/60 border-duck-dark/20 text-duck-dark placeholder:text-duck-dark/40"
            type="password"
            value={clientSecret}
            onChange={(ev) => setClientSecret(ev.target.value)}
            placeholder="GOCSPX-..."
          />
        </Label>

        <Label className="grid gap-2">
          <span className="text-duck-dark/70 dark:text-foreground/70">Redirect URI</span>
          <p className="text-xs text-duck-dark/40 dark:text-foreground/40">
            Add this URI to your Google OAuth client&apos;s authorized redirect URIs
          </p>
          <Input
            className="h-11 bg-background/60 border-duck-dark/20 text-duck-dark/60"
            type="text"
            value={redirectUri}
            readOnly
          />
        </Label>

        <Button
          type="button"
          onClick={handleSave}
          disabled={isSaving || !clientId.trim() || !clientSecret.trim()}
          className="w-full h-11 bg-duck-yellow hover:bg-duck-yellow/90 text-duck-teal font-bold transition-all duration-200 hover:scale-105 cursor-pointer disabled:opacity-50 disabled:hover:scale-100"
        >
          {isSaving ? 'Saving...' : 'Save'}
        </Button>
      </div>
    </div>
  );
};
