import { useState, useEffect } from 'react';
import { toast } from 'sonner';
import { Copy } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useClient } from 'hooks/useClient';

type TelegramConnection = {
  linked: boolean;
  telegramId?: string;
};

type TelegramStatus = {
  configured: boolean;
  running: boolean;
  botUsername: string | null;
  serverInvite: string | null;
  botHandle: string | null;
};

export const TelegramAccount = () => {
  const client = useClient();
  const [isLoading, setIsLoading] = useState(true);
  const [connection, setConnection] = useState<TelegramConnection>({ linked: false });
  const [botStatus, setBotStatus] = useState<TelegramStatus>({
    configured: false,
    running: false,
    botUsername: null,
    serverInvite: null,
    botHandle: null,
  });
  const [pairingCode, setPairingCode] = useState<string | null>(null);
  const [isGenerating, setIsGenerating] = useState(false);

  useEffect(() => {
    Promise.all([
      client.get<TelegramConnection>('/channels/telegram/connection').then(setConnection),
      client.get<TelegramStatus>('/channels/telegram/status').then(setBotStatus),
    ])
      .catch(() => {})
      .finally(() => setIsLoading(false));
  }, []);

  const handleGenerateCode = async () => {
    setIsGenerating(true);
    try {
      const res = await client.post<{ code: string; expiresIn: number }>('/channels/telegram/pair', {});
      setPairingCode(res.code);
    } catch {
      toast.error('Failed to generate pairing code');
    } finally {
      setIsGenerating(false);
    }
  };

  const handleCopyCode = () => {
    if (pairingCode) {
      navigator.clipboard.writeText(pairingCode);
      toast.success('Code copied to clipboard');
    }
  };

  const handleDisconnect = async () => {
    try {
      await client.delete('/channels/telegram/connection');
      setConnection({ linked: false });
      setPairingCode(null);
      toast.success('Telegram account unlinked');
    } catch {
      toast.error('Failed to unlink Telegram account');
    }
  };

  if (isLoading) return null;

  if (!botStatus.configured) {
    return (
      <div className="grid gap-4">
        <p className="text-sm text-duck-dark/60 dark:text-foreground/60">
          Telegram integration has not been configured yet. Ask your administrator to set up the Telegram bot in the
          Enterprise settings.
        </p>
      </div>
    );
  }

  const botHandle = botStatus.botUsername ? `@${botStatus.botUsername}` : botStatus.botHandle;
  const botLink = botStatus.botUsername ? `https://t.me/${botStatus.botUsername}` : null;

  const connectionInfo = (botHandle || botStatus.serverInvite) && (
    <div className="rounded-lg border border-duck-dark/10 dark:border-foreground/10 p-4 grid gap-2">
      {botHandle && (
        <div className="flex items-center gap-2 text-sm">
          <span className="text-duck-dark/50 dark:text-foreground/50 shrink-0">Bot:</span>
          {botLink ? (
            <a href={botLink} target="_blank" rel="noopener noreferrer" className="text-duck-teal underline">
              {botHandle}
            </a>
          ) : (
            <code className="text-xs bg-duck-dark/5 dark:bg-foreground/5 px-2 py-1 rounded">{botHandle}</code>
          )}
        </div>
      )}
      {botStatus.serverInvite && (
        <div className="flex items-center gap-2 text-sm">
          <span className="text-duck-dark/50 dark:text-foreground/50 shrink-0">Group:</span>
          <a
            href={botStatus.serverInvite}
            target="_blank"
            rel="noopener noreferrer"
            className="text-duck-teal underline truncate"
          >
            {botStatus.serverInvite}
          </a>
        </div>
      )}
    </div>
  );

  if (connection.linked) {
    return (
      <div className="grid gap-4">
        <div className="flex items-center gap-3 rounded-lg border border-duck-dark/10 dark:border-foreground/10 p-4">
          <div className="h-2.5 w-2.5 rounded-full bg-green-500 shrink-0" />
          <div className="min-w-0 flex-1">
            <p className="text-sm font-medium text-duck-dark dark:text-foreground">Linked</p>
            <p className="text-xs text-duck-dark/50 dark:text-foreground/50 truncate">
              Telegram ID: {connection.telegramId}
            </p>
          </div>
        </div>
        {connectionInfo}
        <p className="text-xs text-duck-dark/40 dark:text-foreground/40">
          You can send direct messages to the bot on Telegram and they will be handled by your PI agent.
        </p>
        <Button type="button" variant="outline" onClick={handleDisconnect} className="w-full h-11 cursor-pointer">
          Unlink Telegram
        </Button>
      </div>
    );
  }

  return (
    <div className="grid gap-4">
      <p className="text-sm text-duck-dark/60 dark:text-foreground/60">
        Link your Telegram account to chat with your agent via direct messages{botHandle ? ` to ${botHandle}` : ''}.
      </p>

      {connectionInfo}

      {pairingCode ? (
        <div className="grid gap-3">
          <div className="flex items-center justify-between rounded-lg border border-duck-dark/10 dark:border-foreground/10 p-4">
            <code className="text-2xl font-mono font-bold tracking-[0.3em] text-duck-dark dark:text-foreground">
              {pairingCode}
            </code>
            <Button
              type="button"
              variant="ghost"
              size="icon"
              onClick={handleCopyCode}
              className="cursor-pointer shrink-0"
            >
              <Copy className="h-4 w-4" />
            </Button>
          </div>
          <p className="text-xs text-duck-dark/50 dark:text-foreground/50">
            Send this code as a direct message to{' '}
            {botLink ? (
              <a href={botLink} target="_blank" rel="noopener noreferrer" className="text-duck-teal underline">
                {botHandle}
              </a>
            ) : (
              <strong>{botHandle ?? 'the bot'}</strong>
            )}{' '}
            on Telegram. Expires in 10 minutes.
          </p>
          <Button
            type="button"
            variant="outline"
            onClick={handleGenerateCode}
            disabled={isGenerating}
            className="w-full h-11 cursor-pointer"
          >
            Generate New Code
          </Button>
        </div>
      ) : (
        <Button
          type="button"
          onClick={handleGenerateCode}
          disabled={isGenerating}
          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"
        >
          {isGenerating ? 'Generating...' : 'Link Telegram'}
        </Button>
      )}
    </div>
  );
};
