import { useState, useEffect, useCallback } from 'react';
import { X, Check } from 'lucide-react';
import { assetBasePath } from '@/lib/basePath';
import { getStatus, getChannelIdentifier, disconnectChannel } from '@/lib/api';
import type { StatusResponse } from '@/types/api';
import type { ChannelIdentifier } from '@/lib/api';
import { useLocale } from '@/lib/i18n';
import WeChatBind from './WeChatBind';
import WeComBind from './WeComBind';
import DingTalkBind from './DingTalkBind';
import FeishuBind from './FeishuBind';

type ModalChannel = 'wechat' | 'wecom' | 'dingtalk' | 'feishu';

interface ChannelItem {
  name: string;
  icon: string;
  key: ModalChannel;
  status: 'connected' | 'disconnected' | 'unconfigured';
  description: string;
}

function BindModal({ channel, onClose, onBindSuccess }: { channel: ModalChannel; onClose: () => void; onBindSuccess: () => void }) {
  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4 animate-fade-in"
      style={{ background: 'transparent' }}
    >
      <div
        className="relative w-[424px] h-[480px] overflow-y-auto rounded-[12px] shadow-2xl animate-fade-in-scale px-6"
        style={{ background: '#FFFFFF' }}
      >
        <button
          onClick={onClose}
          className="absolute z-10 flex items-center justify-center transition-colors"
          style={{
            width: 30,
            height: 30,
            top: 4,
            right: 4,
            borderRadius: 6,
            background: 'transparent',
            border: 'none',
            cursor: 'pointer',
          }}
          onMouseEnter={(e) => { e.currentTarget.style.background = '#F53F3F'; (e.currentTarget.firstChild as HTMLElement).style.color = '#FFFFFF'; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; (e.currentTarget.firstChild as HTMLElement).style.color = '#000000'; }}
        >
          <X className="h-[14px] w-[14px]" style={{ color: '#000000', transition: 'color 0.15s' }} />
        </button>

        {channel === 'wechat' && <WeChatBind onBindSuccess={onBindSuccess} />}
        {channel === 'wecom' && <WeComBind onBindSuccess={onBindSuccess} />}
        {channel === 'dingtalk' && <DingTalkBind onBindSuccess={onBindSuccess} />}
        {channel === 'feishu' && <FeishuBind onBindSuccess={onBindSuccess} />}
      </div>
    </div>
  );
}

function ConnectedModal({ channel, onClose, onDisconnected }: { channel: ChannelItem; onClose: () => void; onDisconnected: () => void }) {
  const [identifier, setIdentifier] = useState<ChannelIdentifier | null>(null);
  const [disconnecting, setDisconnecting] = useState(false);
  const { t } = useLocale();

  useEffect(() => {
    getChannelIdentifier(channel.key)
      .then(setIdentifier)
      .catch(() => { });
  }, [channel.key]);

  const handleDisconnect = async () => {
    if (disconnecting) return;
    setDisconnecting(true);
    try {
      await disconnectChannel(channel.key);
      onDisconnected();
    } catch {
      setDisconnecting(false);
    }
  };

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4 animate-fade-in"
      style={{ background: 'transparent' }}
    >
      <div
        className="relative w-[424px] rounded-[12px] shadow-2xl animate-fade-in-scale px-6 flex flex-col"
        style={{ background: '#fff', height: 298 }}
      >
        <button
          onClick={onClose}
          className="absolute z-10 flex items-center justify-center transition-colors"
          style={{
            width: 30,
            height: 30,
            top: 4,
            right: 4,
            borderRadius: 6,
            background: 'transparent',
            border: 'none',
            cursor: 'pointer',
          }}
          onMouseEnter={(e) => { e.currentTarget.style.background = '#F53F3F'; (e.currentTarget.firstChild as HTMLElement).style.color = '#FFFFFF'; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; (e.currentTarget.firstChild as HTMLElement).style.color = '#000000'; }}
        >
          <X className="h-[14px] w-[14px]" style={{ color: '#000000', transition: 'color 0.15s' }} />
        </button>

        <div className="flex flex-col items-center pt-8">
          <img src={`${assetBasePath}/icons/${channel.icon}`} alt={channel.name} width="64" height="64" style={{ borderRadius: 16 }} />

          <h2 style={{
            fontFamily: "'Noto Sans CJK SC', sans-serif",
            fontSize: 20,
            fontWeight: 500,
            color: '#000000',
            marginTop: 16,
          }}>
            {channel.name} {t('channel.connected')}
          </h2>

          <div className="flex flex-col items-center" style={{ marginTop: 20 }}>
            <span style={{
              fontFamily: "'Noto Sans CJK SC', sans-serif",
              fontSize: 14,
              fontWeight: 400,
              color: 'rgba(0, 0, 0, 0.45)',
              marginBottom: 4,
            }}>
              {channel.name} {identifier?.label ?? t('channel.bot_id')}：
            </span>
            <span style={{
              fontFamily: "'Noto Sans CJK SC', sans-serif",
              fontSize: 14,
              fontWeight: 400,
              color: 'rgba(0, 0, 0, 0.85)',
            }}>
              {identifier?.value ?? '—'}
            </span>
          </div>
        </div>

        <div className="flex items-center justify-end gap-3" style={{ marginTop: 'auto', paddingBottom: 24 }}>
          <button
            onClick={onClose}
            style={{
              fontFamily: "'Noto Sans CJK SC', sans-serif",
              fontSize: 14,
              fontWeight: 400,
              minWidth: 88,
              padding: '8px 16px',
              borderRadius: 6,
              background: 'rgba(0, 0, 0, 0.04)',
              color: 'rgba(0, 0, 0, 0.85)',
              border: 'none',
              cursor: 'pointer',
              whiteSpace: 'nowrap',
            }}
          >
            {t('channel.confirm')}
          </button>
          <button
            onClick={handleDisconnect}
            disabled={disconnecting}
            style={{
              fontFamily: "'Noto Sans CJK SC', sans-serif",
              fontSize: 14,
              fontWeight: 400,
              minWidth: 88,
              padding: '8px 16px',
              borderRadius: 6,
              background: disconnecting ? 'rgba(245, 63, 63, 0.5)' : '#F53F3F',
              color: '#FFFFFF',
              border: 'none',
              cursor: disconnecting ? 'not-allowed' : 'pointer',
              whiteSpace: 'nowrap',
            }}
          >
            {disconnecting ? t('channel.disconnecting') : t('channel.disconnect')}
          </button>
        </div>
      </div>
    </div>
  );
}

const CHANNEL_KEY_MAP: Record<string, ModalChannel> = {
  WeChat: 'wechat',
  WeCom: 'wecom',
  DingTalk: 'dingtalk',
  Feishu: 'feishu',
};

export default function Channel() {
  const { t } = useLocale();
  const [activeModal, setActiveModal] = useState<ModalChannel | null>(null);
  const [successToast, setSuccessToast] = useState<string | null>(null);

  const channelBase: Omit<ChannelItem, 'status' | 'statusLabel'>[] = [
    {
      name: t('channel.wechat'),
      icon: 'wechat.svg',
      key: 'wechat',
      description: t('channel.wechat.desc'),
    },
    {
      name: t('channel.wecom'),
      icon: 'wecom.svg',
      key: 'wecom',
      description: t('channel.wecom.desc'),
    },
    {
      name: t('channel.dingtalk'),
      icon: 'dingtalk.svg',
      key: 'dingtalk',
      description: t('channel.dingtalk.desc'),
    },
    {
      name: t('channel.feishu'),
      icon: 'feishu.svg',
      key: 'feishu',
      description: t('channel.feishu.desc'),
    },
  ];

  const resolveStatus = (configured: boolean): Pick<ChannelItem, 'status'> => {
    return { status: configured ? 'connected' : 'unconfigured' };
  };

  const statusStyle = (status: ChannelItem['status']) => {
    switch (status) {
      case 'connected':
        return { color: '#00e68a', label: t('channel.connected') };
      case 'disconnected':
        return { color: '#ffaa00', label: t('channel.not_connected') };
      case 'unconfigured':
        return { color: 'var(--pc-text-faint)', label: t('channel.not_configured') };
    }
  };

  const CHANNEL_SUCCESS_TEXT: Record<ModalChannel, string> = {
    wechat: t('channel.wechat.connected'),
    wecom: t('channel.wecom.connected'),
    dingtalk: t('channel.dingtalk.connected'),
    feishu: t('channel.feishu.connected'),
  };

  const CHANNEL_DISCONNECTED_TEXT: Record<ModalChannel, string> = {
    wechat: t('channel.wechat.disconnected'),
    wecom: t('channel.wecom.disconnected'),
    dingtalk: t('channel.dingtalk.disconnected'),
    feishu: t('channel.feishu.disconnected'),
  };

  const [channels, setChannels] = useState<ChannelItem[]>(channelBase.map(c => ({
    ...c,
    status: 'unconfigured' as const,
  })));

  const refreshStatus = useCallback(() => {
    getStatus()
      .then((data: StatusResponse) => {
        const statusMap: Record<ModalChannel, boolean> = { wechat: false, wecom: false, dingtalk: false, feishu: false };
        for (const [backendKey, configured] of Object.entries(data.channels)) {
          const mapped = CHANNEL_KEY_MAP[backendKey];
          if (mapped) statusMap[mapped] = configured;
        }
        setChannels(prev =>
          prev.map(ch => ({
            ...ch,
            ...resolveStatus(statusMap[ch.key]),
          }))
        );
      })
      .catch(() => { });
  }, [CHANNEL_KEY_MAP]);

  useEffect(() => {
    refreshStatus();
  }, [refreshStatus]);

  return (
    <div className="pr-6 pb-6 pl-6 animate-fade-in" style={{ paddingTop: 10, background: '#FFFFFF', minHeight: '100vh' }}>
      <h2 className="mb-2" style={{
        fontSize: 14,
        fontWeight: 400,
        color: 'rgba(0, 0, 0, 0.85)',
        marginLeft: 8,
      }}>{t('channel.title')}</h2>

      <div className="grid grid-cols-2 gap-x-2 gap-y-2 stagger-children">
        {channels.map((channel, idx) => {
          const s = statusStyle(channel.status);
          const radius = 8;
          const cornerStyle: React.CSSProperties = {
            background: '#F6F6F6',
            border: '1px solid var(--pc-border)',
            borderRadius: [
              idx === 0 ? radius : 0,
              idx === 1 ? radius : 0,
              idx === 3 ? radius : 0,
              idx === 2 ? radius : 0,
            ].join('px ') + 'px',
          };
          return (
            <div
              key={channel.key}
              className="px-5 animate-slide-in-up flex items-center gap-4 transition-all"
              style={{ ...cornerStyle, height: 89 }}
            >
              <img
                src={`${assetBasePath}/icons/${channel.icon}`}
                alt={channel.name}
                className="h-8 w-8 shrink-0"
              />

              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 mb-0.5">
                  <span className="text-sm font-semibold" style={{ color: 'var(--pc-text-primary)' }}>
                    {channel.name}
                  </span>
                  <span
                    className="inline-flex items-center justify-center"
                    style={{
                      minWidth: 44,
                      height: 20,
                      padding: '0 8px',
                      borderRadius: 10,
                      background: channel.status === 'connected' ? 'rgba(0, 180, 42, 0.05)' : 'rgba(0, 0, 0, 0.05)',
                      fontSize: 12,
                      fontWeight: 400,
                      color: channel.status === 'connected' ? '#00B42A' : 'rgba(0, 0, 0, 0.65)',
                      whiteSpace: 'nowrap',
                    }}
                  >
                    {s.label}
                  </span>
                </div>
                <p className="text-sm leading-relaxed line-clamp-2" style={{ color: 'var(--pc-text-muted)' }}>
                  {channel.description}
                </p>
              </div>

              <button
                onClick={() => setActiveModal(channel.key)}
                className="shrink-0 rounded-lg text-sm font-medium transition-all flex items-center justify-center"
                style={{
                  minWidth: 64,
                  height: 36,
                  padding: '0 14px',
                  background: 'rgba(0, 0, 0, 0.1)',
                  border: '1px solid var(--pc-border)',
                  color: 'rgba(0, 0, 0, 0.85)',
                  whiteSpace: 'nowrap',
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.background = 'var(--pc-hover)';
                  e.currentTarget.style.borderColor = 'var(--pc-border-strong)';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.background = 'rgba(0, 0, 0, 0.1)';
                  e.currentTarget.style.borderColor = 'var(--pc-border)';
                }}
              >
                {t('channel.configure')}
              </button>
            </div>
          );
        })}
      </div>

      {activeModal && (() => {
        const ch = channels.find(c => c.key === activeModal);
        if (!ch) return null;
        if (ch.status === 'connected') {
          return (
            <ConnectedModal
              channel={ch}
              onClose={() => {
                setActiveModal(null);
                refreshStatus();
              }}
              onDisconnected={() => {
                setActiveModal(null);
                setSuccessToast(CHANNEL_DISCONNECTED_TEXT[ch.key]);
                refreshStatus();
                setTimeout(() => setSuccessToast(null), 3000);
              }}
            />
          );
        }
        return <BindModal channel={activeModal} onClose={() => {
          setActiveModal(null);
          refreshStatus();
        }} onBindSuccess={() => {
          setActiveModal(null);
          setSuccessToast(CHANNEL_SUCCESS_TEXT[activeModal]);
          refreshStatus();
          setTimeout(() => setSuccessToast(null), 3000);
        }} />;
      })()}

      {successToast && (
        <div
          className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-[100] flex items-center gap-2 rounded-lg shadow-lg animate-fade-in-scale"
          style={{
            padding: '18px 16px',
            background: '#FFFFFF',
            border: '1px solid rgba(0,0,0,0.08)',
            fontSize: 14,
            color: 'rgba(0,0,0,0.85)',
            fontWeight: 500,
          }}
        >
          <div
            className="flex items-center justify-center shrink-0 rounded-full"
            style={{ width: 16, height: 16, background: '#10b981' }}
          >
            <Check className="w-[10px] h-[10px]" style={{ color: '#FFFFFF', strokeWidth: 3 }} />
          </div>
          <span>{successToast}</span>
        </div>
      )}
    </div>
  );
}
