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 WhatsAppConnection = {
  linked: boolean;
  whatsappId?: string;
};

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

export const WhatsAppAccount = () => {
  const client = useClient();
  const [isLoading, setIsLoading] = useState(true);
  const [connection, setConnection] = useState<WhatsAppConnection>({ linked: false });
  const [botStatus, setBotStatus] = useState<WhatsAppStatus>({ configured: false, running: false, phone: null });
  const [pairingCode, setPairingCode] = useState<string | null>(null);
  const [isGenerating, setIsGenerating] = useState(false);

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

  const handleGenerateCode = async () => {
    setIsGenerating(true);
    try {
      const res = await client.post<{ code: string; expiresIn: number }>('/channels/whatsapp/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/whatsapp/connection');
      setConnection({ linked: false });
      setPairingCode(null);
      toast.success('WhatsApp account unlinked');
    } catch {
      toast.error('Failed to unlink WhatsApp 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">
          WhatsApp integration has not been configured yet. Ask your administrator to connect WhatsApp in the Enterprise
          settings.
        </p>
      </div>
    );
  }

  const phoneInfo = botStatus.phone && (
    <div className="rounded-lg border border-duck-dark/10 dark:border-foreground/10 p-4 grid gap-2">
      <div className="flex items-center gap-2 text-sm">
        <span className="text-duck-dark/50 dark:text-foreground/50 shrink-0">Bot phone:</span>
        <code className="text-xs bg-duck-dark/5 dark:bg-foreground/5 px-2 py-1 rounded">+{botStatus.phone}</code>
      </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">
              Phone: +{connection.whatsappId}
            </p>
          </div>
        </div>
        {phoneInfo}
        <p className="text-xs text-duck-dark/40 dark:text-foreground/40">
          You can send messages to the bot on WhatsApp 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 WhatsApp
        </Button>
      </div>
    );
  }

  return (
    <div className="grid gap-4">
      <p className="text-sm text-duck-dark/60 dark:text-foreground/60">
        Link your WhatsApp account to chat with your PI agent via direct messages.
      </p>

      {phoneInfo}

      {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 to{botStatus.phone ? ` +${botStatus.phone}` : ' the bot'} on WhatsApp. 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 WhatsApp'}
        </Button>
      )}
    </div>
  );
};
