import { useState, useEffect, useCallback } from 'react';
import type { FC } from 'react';
import TelegramSubNav from '../../components/TelegramSubNav';
import { characters, channels } from '../../api/client';
import type { CharacterSummary, ChannelInfo } from '../../types/telegram';
import { motion } from 'framer-motion';
import { Copy, Send, Settings, Plus } from 'lucide-react';

const inputClass = 'w-full rounded-xl border border-white/[0.06] bg-white/[0.03] px-4 py-2.5 text-sm text-slate-100 placeholder-slate-500 outline-none transition-all focus:border-indigo-500/50 focus:ring-2 focus:ring-indigo-500/20 backdrop-blur-xl';
const selectClass = 'w-full rounded-xl border border-white/[0.06] bg-white/[0.03] px-4 py-2.5 text-sm text-slate-100 outline-none transition-all focus:border-indigo-500/50 focus:ring-2 focus:ring-indigo-500/20 backdrop-blur-xl';
const glassCard = 'rounded-2xl border border-white/[0.06] bg-white/[0.03] backdrop-blur-xl';

const Channels: FC = () => {
  const [charList, setCharList] = useState<CharacterSummary[]>([]); const [selectedCharId, setSelectedCharId] = useState<string | null>(null);
  const [channelInfo, setChannelInfo] = useState<ChannelInfo | null>(null); const [loading, setLoading] = useState(true); const [channelLoading, setChannelLoading] = useState(false);
  const [error, setError] = useState<string | null>(null); const [showCreate, setShowCreate] = useState(false);
  const [normalTitle, setNormalTitle] = useState(''); const [vipTitle, setVipTitle] = useState('');
  const [publishMode, setPublishMode] = useState<'normal' | 'vip' | null>(null); const [publishText, setPublishText] = useState(''); const [publishPhoto, setPublishPhoto] = useState(''); const [publishStars, setPublishStars] = useState(50);
  const [editMode, setEditMode] = useState<'normal' | 'vip' | null>(null); const [editCron, setEditCron] = useState(''); const [editStarPrice, setEditStarPrice] = useState(50);

  const fetchChars = useCallback(async () => { try { setLoading(true); const res = await characters.list(); const data = res.data?.data ?? res.data ?? []; setCharList(Array.isArray(data) ? data : []); } catch { setError('Karakter listesi yüklenemedi.'); } finally { setLoading(false); } }, []);
  useEffect(() => { fetchChars(); }, [fetchChars]);
  const fetchChannels = useCallback(async (charId: string) => { setChannelLoading(true); setChannelInfo(null); try { const res = await channels.get(charId); setChannelInfo(res.data?.data ?? res.data?.channels ?? res.data ?? null); } catch { setChannelInfo(null); } setChannelLoading(false); }, []);
  useEffect(() => { if (selectedCharId) fetchChannels(selectedCharId); }, [selectedCharId, fetchChannels]);

  const handleCreate = async () => { if (!selectedCharId) return; try { await channels.create(selectedCharId, { normalTitle: normalTitle || undefined, vipTitle: vipTitle || undefined }); setShowCreate(false); setNormalTitle(''); setVipTitle(''); await fetchChannels(selectedCharId); } catch { setError('Kanal oluşturulamadı.'); } };
  const handlePublish = async (type: 'normal' | 'vip') => { if (!selectedCharId) return; try { const data = type === 'normal' ? { text: publishText || undefined, photoUrl: publishPhoto || undefined, caption: publishText || undefined } : { imageUrl: publishPhoto || undefined, starCount: publishStars, caption: publishText || undefined }; await channels.publish(selectedCharId, type, data); setPublishMode(null); setPublishText(''); setPublishPhoto(''); } catch { setError('Yayın başarısız.'); } };
  const handleUpdateSettings = async (type: 'normal' | 'vip') => { if (!selectedCharId) return; try { const data: Record<string, unknown> = {}; if (editCron) data.schedule = editCron; if (type === 'vip') data.starPrice = editStarPrice; await channels.updateSettings(selectedCharId, type, data); setEditMode(null); await fetchChannels(selectedCharId); } catch { setError('Ayarlar güncellenemedi.'); } };
  const copyToClipboard = (text: string) => { navigator.clipboard.writeText(text).catch(() => {}); };

  const renderChannel = (label: string, ch?: ChannelInfo['normal'] | ChannelInfo['vip'], type: 'normal' | 'vip' = 'normal') => (
    <div className={`${glassCard} p-5`}><h3 className="mb-4 text-base font-semibold text-slate-100">{label}</h3>
      {ch ? (<div className="space-y-3 text-sm text-slate-300">
        <div className="flex justify-between"><span className="text-slate-500">Başlık:</span><span>{ch.title ?? '—'}</span></div>
        <div className="flex justify-between"><span className="text-slate-500">Chat ID:</span><span className="font-mono text-xs">{ch.chatId ?? '—'}</span></div>
        <div className="flex justify-between"><span className="text-slate-500">Üye:</span><span>{ch.memberCount ?? 0}</span></div>
        {ch.inviteLink && <div className="flex items-center justify-between"><span className="text-slate-500">Davet Linki:</span><div className="flex items-center gap-2"><span className="max-w-[200px] truncate font-mono text-xs text-indigo-400">{ch.inviteLink}</span><button onClick={() => copyToClipboard(ch.inviteLink!)} className="flex items-center gap-1 rounded-lg bg-white/[0.06] px-2 py-1 text-xs text-slate-300 transition-colors hover:bg-white/[0.1]"><Copy size={12} /></button></div></div>}
        {type === 'vip' && 'starPrice' in (ch as any) && <div className="flex justify-between"><span className="text-slate-500">Star Fiyatı:</span><span>⭐ {(ch as any).starPrice}</span></div>}
        <div className="flex gap-2 pt-2">
          <button onClick={() => setPublishMode(type)} className="flex items-center gap-1.5 rounded-xl bg-indigo-500/10 px-4 py-2 text-xs font-medium text-indigo-400 transition-colors hover:bg-indigo-500/20"><Send size={14} /> Yayınla</button>
          <button onClick={() => { setEditMode(type); setEditCron(''); setEditStarPrice((ch as any)?.starPrice ?? 50); }} className="flex items-center gap-1.5 rounded-xl bg-amber-500/10 px-4 py-2 text-xs font-medium text-amber-400 transition-colors hover:bg-amber-500/20"><Settings size={14} /> Ayarlar</button>
        </div>
      </div>) : <p className="text-sm text-slate-400">Oluşturulmamış</p>}
    </div>
  );

  return (
    <div>
      <TelegramSubNav />
      <motion.h1 initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="mb-6 text-2xl font-bold bg-gradient-to-r from-indigo-400 via-violet-400 to-purple-400 bg-clip-text text-transparent">📢 Kanal Yönetimi</motion.h1>
      {error && <div className="mb-4 rounded-xl border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-400"><p>{error}</p><button onClick={() => setError(null)} className="mt-2 rounded-xl bg-gradient-to-r from-indigo-500 to-violet-500 px-4 py-2 text-sm font-semibold text-white shadow-lg shadow-indigo-500/25">Kapat</button></div>}
      {loading ? <div className="flex min-h-[30vh] items-center justify-center"><div className="h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent" /></div> : (<>
        <div className="mb-6"><label className="mb-1.5 block text-sm font-medium text-slate-400">Karakter Seçin</label><select value={selectedCharId ?? ''} onChange={e => setSelectedCharId(e.target.value || null)} className={`max-w-md ${selectClass}`}><option value="">— Karakter seçin —</option>{charList.map(c => <option key={c.id} value={c.id}>{c.identity?.name ?? c.id}</option>)}</select></div>
        {selectedCharId && (<>{channelLoading ? <div className="flex min-h-[20vh] items-center justify-center"><div className="h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent" /></div> : (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="space-y-4">
            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">{renderChannel('📢 Normal Kanal', channelInfo?.normal, 'normal')}{renderChannel('👑 VIP Kanal', channelInfo?.vip, 'vip')}</div>
            {!channelInfo?.normal && !channelInfo?.vip && (<div>{!showCreate ? (
              <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={() => setShowCreate(true)} className="flex items-center gap-2 rounded-xl bg-gradient-to-r from-indigo-500 to-violet-500 px-5 py-2.5 text-sm font-semibold text-white shadow-lg shadow-indigo-500/25"><Plus size={16} /> Kanal Oluştur</motion.button>
            ) : (
              <div className={`${glassCard} p-5`}><div className="mb-4 grid grid-cols-2 gap-4"><input placeholder="Normal Kanal Başlığı" value={normalTitle} onChange={e => setNormalTitle(e.target.value)} className={inputClass} /><input placeholder="VIP Kanal Başlığı" value={vipTitle} onChange={e => setVipTitle(e.target.value)} className={inputClass} /></div>
                <div className="flex gap-3"><motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={handleCreate} className="rounded-xl bg-gradient-to-r from-emerald-500 to-teal-500 px-5 py-2.5 text-sm font-semibold text-white shadow-lg shadow-emerald-500/25">Oluştur</motion.button><button onClick={() => setShowCreate(false)} className="rounded-xl border border-white/[0.06] bg-white/[0.03] px-5 py-2.5 text-sm font-medium text-slate-300 transition-all hover:bg-white/[0.06]">İptal</button></div>
              </div>
            )}</div>)}
            {publishMode && (<div className={`${glassCard} p-5`}><h3 className="mb-4 text-sm font-semibold text-slate-100">{publishMode === 'normal' ? '📢 Normal Kanal Yayını' : '👑 VIP Kanal Yayını'}</h3>
              <textarea placeholder="Metin / Açıklama" value={publishText} onChange={e => setPublishText(e.target.value)} className="mb-3 w-full rounded-xl border border-white/[0.06] bg-white/[0.03] px-4 py-2.5 text-sm text-slate-100 placeholder-slate-500 outline-none transition-all focus:border-indigo-500/50 focus:ring-2 focus:ring-indigo-500/20 min-h-[80px] resize-y" />
              <input placeholder="Fotoğraf / Görsel URL" value={publishPhoto} onChange={e => setPublishPhoto(e.target.value)} className={`mb-3 ${inputClass}`} />
              {publishMode === 'vip' && <input type="number" placeholder="Star Sayısı" value={publishStars} onChange={e => setPublishStars(parseInt(e.target.value) || 0)} className={`mb-3 w-32 ${inputClass}`} />}
              <div className="flex gap-3"><motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={() => handlePublish(publishMode)} className="rounded-xl bg-gradient-to-r from-emerald-500 to-teal-500 px-5 py-2.5 text-sm font-semibold text-white shadow-lg shadow-emerald-500/25">Yayınla</motion.button><button onClick={() => setPublishMode(null)} className="rounded-xl border border-white/[0.06] bg-white/[0.03] px-5 py-2.5 text-sm font-medium text-slate-300 transition-all hover:bg-white/[0.06]">İptal</button></div>
            </div>)}
            {editMode && (<div className={`${glassCard} p-5`}><h3 className="mb-4 text-sm font-semibold text-slate-100">{editMode === 'normal' ? '📢 Normal Kanal Ayarları' : '👑 VIP Kanal Ayarları'}</h3>
              <input placeholder="Yayın Zamanlaması (cron)" value={editCron} onChange={e => setEditCron(e.target.value)} className={`mb-3 ${inputClass}`} />
              {editMode === 'vip' && <input type="number" placeholder="Star Fiyatı" value={editStarPrice} onChange={e => setEditStarPrice(parseInt(e.target.value) || 0)} className={`mb-3 w-32 ${inputClass}`} />}
              <div className="flex gap-3"><motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={() => handleUpdateSettings(editMode)} className="rounded-xl bg-gradient-to-r from-emerald-500 to-teal-500 px-5 py-2.5 text-sm font-semibold text-white shadow-lg shadow-emerald-500/25">Kaydet</motion.button><button onClick={() => setEditMode(null)} className="rounded-xl border border-white/[0.06] bg-white/[0.03] px-5 py-2.5 text-sm font-medium text-slate-300 transition-all hover:bg-white/[0.06]">İptal</button></div>
            </div>)}
          </motion.div>
        )}</>)}
      </>)}
    </div>
  );
};

export default Channels;