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 TelegramConfig = {
  configured: boolean;
  enabled: boolean;
  botToken: string | null;
  serverInvite: string | null;
  botHandle: string | null;
};

type TelegramStatus = {
  configured: boolean;
  enabled: boolean;
  running: boolean;
  botUsername: 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">Open Telegram and search for @BotFather</strong>
            <p className="mt-1">
              BotFather is Telegram&apos;s official bot for creating and managing bots. Open Telegram and search for{' '}
              <strong>@BotFather</strong>, then start a conversation.
            </p>
          </li>

          <li>
            <strong className="text-duck-dark dark:text-foreground">Create a new bot</strong>
            <p className="mt-1">
              Send <code className="text-xs bg-duck-dark/5 dark:bg-foreground/5 px-1.5 py-0.5 rounded">/newbot</code> to
              BotFather. Follow the prompts to choose a <strong>display name</strong> and a <strong>username</strong>{' '}
              (must end in &quot;bot&quot;, e.g.{' '}
              <code className="text-xs bg-duck-dark/5 dark:bg-foreground/5 px-1.5 py-0.5 rounded">my_officer_bot</code>
              ).
            </p>
          </li>

          <li>
            <strong className="text-duck-dark dark:text-foreground">Copy the bot token</strong>
            <p className="mt-1">BotFather will reply with an HTTP API token. Copy it — you&apos;ll paste it below.</p>
            <p className="mt-2 text-xs text-duck-dark/50 dark:text-foreground/50">
              Keep this token secret. Anyone with this token can control your bot. You can regenerate it via BotFather
              at any time.
            </p>
          </li>

          <li>
            <strong className="text-duck-dark dark:text-foreground">Optionally create a group</strong>
            <p className="mt-1">
              You can create a Telegram group and add the bot so your team can find it easily. This is optional — users
              can also search for the bot by username and message it directly.
            </p>
          </li>

          <li>
            <strong className="text-duck-dark dark:text-foreground">Paste the token below and save</strong>
            <p className="mt-1">
              Paste the bot token into the field below and click <strong>Save</strong>. The bot will come online
              automatically. Users can then link their Telegram accounts from their personal integration settings.
            </p>
          </li>
        </ol>
      </CollapsibleContent>
    </Collapsible>
  );
};

export const TelegramBotConfig = () => {
  const client = useClient();
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [isToggling, setIsToggling] = useState(false);
  const [botToken, setBotToken] = useState('');
  const [serverInvite, setServerInvite] = useState('');
  const [botHandle, setBotHandle] = useState('');
  const [status, setStatus] = useState<TelegramStatus | null>(null);

  const fetchStatus = () => {
    client
      .get<TelegramStatus>('/channels/telegram/status')
      .then(setStatus)
      .catch(() => {});
  };

  useEffect(() => {
    Promise.all([
      client.get<TelegramConfig>('/channels/telegram/config').then((data) => {
        if (data.botToken) setBotToken(data.botToken);
        if (data.serverInvite) setServerInvite(data.serverInvite);
        if (data.botHandle) setBotHandle(data.botHandle);
      }),
      client.get<TelegramStatus>('/channels/telegram/status').then(setStatus),
    ])
      .catch(() => {})
      .finally(() => setIsLoading(false));
  }, []);

  const handleSave = async () => {
    if (isSaving) return;
    setIsSaving(true);
    try {
      await client.put('/channels/telegram/config', {
        botToken: botToken.trim(),
        serverInvite: serverInvite.trim() || undefined,
        botHandle: botHandle.trim() || undefined,
        enabled: true,
      });
      toast.success('Telegram bot configuration saved');
      fetchStatus();
    } catch {
      toast.error('Failed to save Telegram bot configuration');
    } finally {
      setIsSaving(false);
    }
  };

  const handleDisconnect = async () => {
    setIsToggling(true);
    try {
      await client.put('/channels/telegram/config', { enabled: false });
      toast.success('Telegram bot disconnected');
      fetchStatus();
    } catch {
      toast.error('Failed to disconnect Telegram bot');
    } finally {
      setIsToggling(false);
    }
  };

  const handleConnect = async () => {
    setIsToggling(true);
    try {
      await client.put('/channels/telegram/config', { enabled: true });
      toast.success('Telegram bot connected');
      fetchStatus();
    } catch {
      toast.error('Failed to connect Telegram bot');
    } finally {
      setIsToggling(false);
    }
  };

  if (isLoading) return null;

  return (
    <div className="grid gap-5">
      {status && (
        <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.running ? 'bg-green-500' : 'bg-duck-dark/20 dark:bg-foreground/20'}`}
          />
          <span className="text-sm text-duck-dark dark:text-foreground">
            {status.running
              ? `Online as @${status.botUsername}`
              : status.configured
                ? status.enabled
                  ? 'Bot configured but not running'
                  : 'Disconnected'
                : 'Not configured'}
          </span>
        </div>
      )}

      <SetupGuide />

      <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">Bot Token</span>
          <Input
            className="h-11 bg-background/60 border-duck-dark/20 text-duck-dark placeholder:text-duck-dark/40"
            type="password"
            value={botToken}
            onChange={(ev) => setBotToken(ev.target.value)}
            placeholder="123456:ABC-DEF..."
          />
        </Label>

        <Label className="grid gap-2">
          <span className="text-duck-dark/70 dark:text-foreground/70">Group Invite Link</span>
          <Input
            className="h-11 bg-background/60 border-duck-dark/20 text-duck-dark placeholder:text-duck-dark/40"
            value={serverInvite}
            onChange={(ev) => setServerInvite(ev.target.value)}
            placeholder="https://t.me/+..."
          />
          <span className="text-xs text-duck-dark/40 dark:text-foreground/40">
            Shown to users so they can join the group and find the bot.
          </span>
        </Label>

        <Label className="grid gap-2">
          <span className="text-duck-dark/70 dark:text-foreground/70">Bot Handle</span>
          <Input
            className="h-11 bg-background/60 border-duck-dark/20 text-duck-dark placeholder:text-duck-dark/40"
            value={botHandle}
            onChange={(ev) => setBotHandle(ev.target.value)}
            placeholder="@my_officer_bot"
          />
          <span className="text-xs text-duck-dark/40 dark:text-foreground/40">
            The bot&apos;s @username — shown to users who want to message the bot directly.
          </span>
        </Label>

        <Button
          type="button"
          onClick={handleSave}
          disabled={isSaving || !botToken.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>

        {status?.running ? (
          <Button
            type="button"
            variant="outline"
            onClick={handleDisconnect}
            disabled={isToggling}
            className="w-full h-11 cursor-pointer"
          >
            {isToggling ? 'Disconnecting...' : 'Disconnect'}
          </Button>
        ) : status?.configured && !status.enabled ? (
          <Button
            type="button"
            variant="outline"
            onClick={handleConnect}
            disabled={isToggling}
            className="w-full h-11 cursor-pointer"
          >
            {isToggling ? 'Connecting...' : 'Connect'}
          </Button>
        ) : null}
      </div>
    </div>
  );
};
