import { Plug, PlugZap, Trash2 } from 'lucide-react';

import { useState } from 'react';

import { Head, useForm } from '@inertiajs/react';
import { router } from '@inertiajs/react';

import ConnectionStatusBadge from '@/Components/Connections/ConnectionStatusBadge';
import InputError from '@/Components/InputError';
import EditorialPageHeader from '@/Components/layout/EditorialPageHeader';
import { Alert, AlertDescription, AlertTitle } from '@/Components/ui/alert';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { ConfirmDialog } from '@/Components/ui/confirm-dialog';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { LoadingButton } from '@/Components/ui/loading-button';
import { Textarea } from '@/Components/ui/textarea';
import { useFlashToasts } from '@/hooks/useFlashToasts';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { formatDateTime } from '@/lib/format';
import type { PageProps, SiteSummary } from '@/types';

interface Ga4ConnectionData {
  property_id: string;
  sync_status: string;
  sync_error: string | null;
  last_synced_at: string | null;
  last_sync_failed_at: string | null;
}

interface Props extends PageProps {
  site: SiteSummary;
  has_connection: boolean;
  ga4_connection: Ga4ConnectionData | null;
}

export default function Ga4Connection({ site, has_connection, ga4_connection }: Props) {
  useFlashToasts();

  const [showDisconnect, setShowDisconnect] = useState(false);
  const [testingConnection, setTestingConnection] = useState(false);

  const connectForm = useForm({
    property_id: '',
    api_key: '',
    service_account_json: '',
  });

  const disconnectForm = useForm({});

  function handleConnect(e: React.FormEvent) {
    e.preventDefault();
    connectForm.post(route('sites.settings.ga4.store', site.id), {
      onSuccess: () => connectForm.reset(),
    });
  }

  function handleDisconnect() {
    disconnectForm.delete(route('sites.settings.ga4.destroy', site.id), {
      onFinish: () => setShowDisconnect(false),
    });
  }

  /**
   * GA4-CONNECT-REACHABLE: Test-connection action.
   * Fire-and-forget (gotcha #11 — never await router.*).
   */
  function handleTestConnection() {
    setTestingConnection(true);
    router.post(
      route('sites.settings.ga4.test', site.id),
      {},
      {
        onFinish: () => setTestingConnection(false),
        onError: () => setTestingConnection(false),
      },
    );
  }

  return (
    <>
      <Head title="GA4 Connection" />

      <div className="container max-w-3xl py-8">
        <EditorialPageHeader
          title="Google Analytics 4"
          subtitle="Connect your GA4 property to track AI-referral traffic and measure content recovery impact."
        />

        {/* ── Current connection status ─────────────────────────────────── */}
        {has_connection && ga4_connection ? (
          <Card className="mb-6">
            <CardHeader>
              <div className="flex items-start justify-between gap-4">
                <div>
                  <CardTitle className="flex items-center gap-2">
                    <PlugZap className="size-4 text-success-strong" />
                    GA4 Property Connected
                  </CardTitle>
                  <CardDescription className="mt-1">
                    Property: <span className="font-mono">{ga4_connection.property_id}</span>
                  </CardDescription>
                </div>
                <Button
                  variant="outline"
                  size="sm"
                  className="shrink-0 text-destructive hover:text-destructive"
                  onClick={() => setShowDisconnect(true)}
                >
                  <Trash2 className="mr-1.5 size-3.5" />
                  Disconnect
                </Button>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* GA4-CONNECT-REACHABLE: status badge + honest pending copy */}
              <div className="flex items-center gap-3">
                <span className="text-sm font-medium text-foreground">Status:</span>
                <ConnectionStatusBadge
                  status={
                    ga4_connection.sync_status === 'synced'
                      ? 'synced'
                      : ga4_connection.sync_status === 'failed'
                        ? 'failed'
                        : 'pending'
                  }
                />
                {ga4_connection.sync_status === 'pending' && (
                  <span className="text-xs text-muted-foreground">
                    (Pending verification — click &ldquo;Test connection&rdquo; to verify credentials)
                  </span>
                )}
              </div>

              {/* Test connection CTA — GA4-CONNECT-REACHABLE honesty gate */}
              <LoadingButton
                variant="outline"
                size="sm"
                loading={testingConnection}
                onClick={handleTestConnection}
                data-testid="ga4-test-connection-btn"
              >
                Test connection
              </LoadingButton>

              {/* Last synced timestamp */}
              {ga4_connection.last_synced_at && (
                <p className="text-sm text-muted-foreground">
                  Last synced: {formatDateTime(ga4_connection.last_synced_at)}
                </p>
              )}

              {/* Sync error — shown when probe or nightly import fails */}
              {ga4_connection.sync_status === 'failed' && ga4_connection.sync_error && (
                <Alert variant="destructive">
                  <AlertTitle>Connection failed</AlertTitle>
                  <AlertDescription>
                    {ga4_connection.sync_error}
                    <p className="mt-2 text-xs">
                      Update your credentials below and click &ldquo;Test connection&rdquo; to retry.
                    </p>
                  </AlertDescription>
                </Alert>
              )}
            </CardContent>
          </Card>
        ) : (
          <Alert className="mb-6">
            <Plug className="size-4" />
            <AlertTitle>Not connected</AlertTitle>
            <AlertDescription>
              Connect a GA4 property below. After saving, click &ldquo;Test connection&rdquo; to
              verify your credentials before the nightly import runs.
            </AlertDescription>
          </Alert>
        )}

        {/* ── Connect / update form ─────────────────────────────────────── */}
        <Card>
          <CardHeader>
            <CardTitle>{has_connection ? 'Update credentials' : 'Connect a GA4 property'}</CardTitle>
            <CardDescription>
              Provide your GA4 Property ID and either an API key or a service account JSON.
              Credentials are encrypted at rest.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleConnect} className="space-y-4">
              {/* Property ID */}
              <div className="space-y-1.5">
                <Label htmlFor="property_id">
                  Property ID <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="property_id"
                  placeholder="properties/123456789"
                  value={connectForm.data.property_id}
                  onChange={(e) => connectForm.setData('property_id', e.target.value)}
                />
                <InputError message={connectForm.errors.property_id} />
              </div>

              {/* API key */}
              <div className="space-y-1.5">
                <Label htmlFor="api_key">API Key</Label>
                <Input
                  id="api_key"
                  type="password"
                  placeholder="AIzaSy…"
                  value={connectForm.data.api_key}
                  onChange={(e) => connectForm.setData('api_key', e.target.value)}
                />
                <InputError message={connectForm.errors.api_key} />
              </div>

              {/* Service account JSON */}
              <div className="space-y-1.5">
                <Label htmlFor="service_account_json">
                  Service Account JSON{' '}
                  <span className="text-muted-foreground">(alternative to API key)</span>
                </Label>
                <Textarea
                  id="service_account_json"
                  rows={5}
                  placeholder={'{\n  "type": "service_account",\n  …\n}'}
                  className="font-mono text-xs"
                  value={connectForm.data.service_account_json}
                  onChange={(e) => connectForm.setData('service_account_json', e.target.value)}
                />
                <InputError message={connectForm.errors.service_account_json} />
              </div>

              <LoadingButton type="submit" loading={connectForm.processing}>
                {has_connection ? 'Update connection' : 'Connect'}
              </LoadingButton>
            </form>
          </CardContent>
        </Card>

        {/* ── Disconnect confirm ────────────────────────────────────────── */}
        <ConfirmDialog
          open={showDisconnect}
          onOpenChange={setShowDisconnect}
          title="Disconnect GA4?"
          description="The nightly import will stop. Existing ai_referral_metrics rows are kept. You can reconnect at any time."
          confirmLabel="Disconnect"
          variant="destructive"
          onConfirm={handleDisconnect}
        />
      </div>
    </>
  );
}

Ga4Connection.layout = (page: React.ReactNode) => <DashboardLayout>{page}</DashboardLayout>;
