import { useState, useEffect, useRef, useCallback } from 'react';
import { toast } from 'sonner';
import { ChevronDown } from 'lucide-react';
import QRCode from 'qrcode';
import { Button } from '@/components/ui/button';
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@/components/ui/collapsible';
import { useClient } from 'hooks/useClient';

type WhatsAppConfig = {
  configured: boolean;
  enabled: boolean;
  running: boolean;
  phone: string | null;
};

type QRResponse = {
  qr: string | null;
  running: boolean;
  phone: string | null;
};

const SetupGuide = () => {
  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">Click &quot;Connect WhatsApp&quot; below</strong>
            <p className="mt-1">This will start the WhatsApp Web client and generate a QR code.</p>
          </li>

          <li>
            <strong className="text-duck-dark dark:text-foreground">Open WhatsApp on your phone</strong>
            <p className="mt-1">
              Go to <strong>Settings</strong> → <strong>Linked Devices</strong> → <strong>Link a Device</strong>.
            </p>
          </li>

          <li>
            <strong className="text-duck-dark dark:text-foreground">Scan the QR code</strong>
            <p className="mt-1">
              Point your phone camera at the QR code shown below. The bot will come online automatically once scanned.
            </p>
          </li>

          <li>
            <strong className="text-duck-dark dark:text-foreground">Done</strong>
            <p className="mt-1">
              Users can then link their WhatsApp accounts from their personal integration settings and chat via direct
              messages.
            </p>
            <p className="mt-2 text-xs text-duck-dark/50 dark:text-foreground/50">
              The session persists across restarts — you won&apos;t need to re-scan unless you disconnect.
            </p>
          </li>
        </ol>
      </CollapsibleContent>
    </Collapsible>
  );
};

export const WhatsAppBotConfig = () => {
  const client = useClient();
  const [isLoading, setIsLoading] = useState(true);
  const [config, setConfig] = useState<WhatsAppConfig | null>(null);
  const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
  const [isConnecting, setIsConnecting] = useState(false);
  const [isDisconnecting, setIsDisconnecting] = useState(false);
  const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const fetchConfig = useCallback(() => {
    client
      .get<WhatsAppConfig>('/channels/whatsapp/config')
      .then(setConfig)
      .catch(() => {});
  }, [client]);

  const stopPolling = useCallback(() => {
    if (pollingRef.current) {
      clearInterval(pollingRef.current);
      pollingRef.current = null;
    }
  }, []);

  const pollQR = useCallback(() => {
    client
      .get<QRResponse>('/channels/whatsapp/qr')
      .then(async (data) => {
        if (data.running) {
          // Authenticated — stop polling, update config
          stopPolling();
          setQrDataUrl(null);
          fetchConfig();
          return;
        }
        if (data.qr) {
          const dataUrl = await QRCode.toDataURL(data.qr, { width: 256, margin: 2 });
          setQrDataUrl(dataUrl);
        }
      })
      .catch(() => {});
  }, [client, fetchConfig, stopPolling]);

  const startPolling = useCallback(() => {
    stopPolling();
    pollQR();
    pollingRef.current = setInterval(pollQR, 2000);
  }, [pollQR, stopPolling]);

  useEffect(() => {
    client
      .get<WhatsAppConfig>('/channels/whatsapp/config')
      .then((data) => {
        setConfig(data);
        // Auto-poll QR if bot is enabled but waiting for scan
        if (data.enabled && !data.running) {
          startPolling();
        }
      })
      .catch(() => {})
      .finally(() => setIsLoading(false));

    return stopPolling;
  }, []);

  const handleConnect = async () => {
    setIsConnecting(true);
    try {
      await client.put('/channels/whatsapp/config', { enabled: true });
      startPolling();
    } catch {
      toast.error('Failed to start WhatsApp connection');
    } finally {
      setIsConnecting(false);
    }
  };

  const handleDisconnect = async () => {
    setIsDisconnecting(true);
    try {
      await client.put('/channels/whatsapp/config', { enabled: false });
      stopPolling();
      setQrDataUrl(null);
      toast.success('WhatsApp disconnected');
      fetchConfig();
    } catch {
      toast.error('Failed to disconnect WhatsApp');
    } finally {
      setIsDisconnecting(false);
    }
  };

  if (isLoading) return null;

  return (
    <div className="grid gap-5">
      {config && (
        <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 ${config.running ? 'bg-green-500' : 'bg-duck-dark/20 dark:bg-foreground/20'}`}
          />
          <span className="text-sm text-duck-dark dark:text-foreground">
            {config.running
              ? `Connected as +${config.phone}`
              : config.enabled
                ? 'Waiting for QR scan...'
                : 'Not connected'}
          </span>
        </div>
      )}

      <SetupGuide />

      <div className="border-t border-duck-dark/10 dark:border-foreground/10 pt-5 grid gap-5">
        {qrDataUrl && (
          <div className="flex flex-col items-center gap-3">
            <img
              src={qrDataUrl}
              alt="WhatsApp QR Code"
              className="rounded-lg border border-duck-dark/10 dark:border-foreground/10"
            />
            <p className="text-sm text-duck-dark/60 dark:text-foreground/60">Scan this QR code with WhatsApp</p>
          </div>
        )}

        {config?.running || config?.enabled ? (
          <Button
            type="button"
            variant="outline"
            onClick={handleDisconnect}
            disabled={isDisconnecting}
            className="w-full h-11 cursor-pointer"
          >
            {isDisconnecting ? 'Disconnecting...' : 'Disconnect WhatsApp'}
          </Button>
        ) : (
          <Button
            type="button"
            onClick={handleConnect}
            disabled={isConnecting}
            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"
          >
            {isConnecting ? 'Connecting...' : 'Connect WhatsApp'}
          </Button>
        )}
      </div>
    </div>
  );
};
