'use client';

import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { FiPlus, FiEdit2, FiTrash2, FiRadio } from 'react-icons/fi';
import AdminTable from '@/components/admin/AdminTable';
import AdminModal from '@/components/admin/AdminModal';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import Badge from '@/components/ui/Badge';
import Dropdown from '@/components/ui/Dropdown';
import { CHANNEL_CATEGORIES } from '@/lib/constants';
import toast from 'react-hot-toast';
import type { TableColumn } from '@/types';

interface ChannelRow { id: string; name: string; number: number; category: string; streamUrl: string; isLive: boolean; viewers: number; currentProgram: string; [key: string]: unknown; }

const mockChannelsData: ChannelRow[] = [
  { id: 'ch1', name: 'ESPN Deportes', number: 1, category: 'Deportes', streamUrl: 'https://stream.espn.com/live', isLive: true, viewers: 12450, currentProgram: 'Liga MX en Vivo' },
  { id: 'ch2', name: 'CNN en Español', number: 2, category: 'Noticias', streamUrl: 'https://stream.cnn.com/live', isLive: true, viewers: 8320, currentProgram: 'Noticias Hoy' },
  { id: 'ch3', name: 'Discovery Channel', number: 3, category: 'Documentales', streamUrl: 'https://stream.discovery.com/live', isLive: true, viewers: 5640, currentProgram: 'Planeta Tierra' },
  { id: 'ch4', name: 'Cartoon Network', number: 4, category: 'Infantiles', streamUrl: 'https://stream.cn.com/live', isLive: true, viewers: 7890, currentProgram: 'Hora de Aventura' },
  { id: 'ch5', name: 'Fox Sports', number: 5, category: 'Deportes', streamUrl: 'https://stream.fox.com/live', isLive: true, viewers: 15230, currentProgram: 'NFL Highlights' },
  { id: 'ch6', name: 'MTV Hits', number: 6, category: 'Música', streamUrl: 'https://stream.mtv.com/live', isLive: true, viewers: 3210, currentProgram: 'Top 20' },
  { id: 'ch7', name: 'History Channel', number: 7, category: 'Documentales', streamUrl: 'https://stream.history.com/live', isLive: false, viewers: 0, currentProgram: 'Off Air' },
  { id: 'ch8', name: 'Nat Geo Wild', number: 8, category: 'Documentales', streamUrl: 'https://stream.natgeo.com/live', isLive: true, viewers: 3890, currentProgram: 'Depredadores' },
  { id: 'ch9', name: 'Nickelodeon', number: 9, category: 'Infantiles', streamUrl: 'https://stream.nick.com/live', isLive: true, viewers: 9120, currentProgram: 'Bob Esponja' },
  { id: 'ch10', name: 'TNT Sports', number: 11, category: 'Deportes', streamUrl: 'https://stream.tnt.com/live', isLive: true, viewers: 18900, currentProgram: 'Champions League' },
];

const channelColumns: TableColumn<ChannelRow>[] = [
  { key: 'number', label: '#', sortable: true, width: '60px' },
  { key: 'name', label: 'Canal', sortable: true },
  { key: 'category', label: 'Categoría', sortable: true, render: (item) => <Badge variant="neutral" size="sm">{item.category}</Badge> },
  {
    key: 'isLive', label: 'Estado',
    render: (item) => (
      <Badge variant={item.isLive ? 'success' : 'danger'} size="sm">
        {item.isLive && <span className="w-1.5 h-1.5 bg-green-400 rounded-full animate-pulse" />}
        {item.isLive ? 'En vivo' : 'Off'}
      </Badge>
    ),
  },
  { key: 'currentProgram', label: 'Programa Actual', render: (item) => <span className="text-white/50 text-sm truncate max-w-[160px] block">{item.currentProgram}</span> },
  { key: 'viewers', label: 'Espectadores', sortable: true, render: (item) => <span className="text-white/50">{item.viewers.toLocaleString()}</span> },
];

export default function AdminChannelsPage() {
  const [showModal, setShowModal] = useState(false);
  const [newChannel, setNewChannel] = useState({ name: '', number: '', streamUrl: '', categoryId: 'deportes', description: '' });

  const categoryOptions = CHANNEL_CATEGORIES.filter(c => c.id !== 'all').map(c => ({ value: c.id, label: c.name }));

  return (
    <div className="space-y-6">
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        className="flex items-center justify-between flex-wrap gap-4"
      >
        <div>
          <h1 className="text-2xl md:text-3xl font-bold text-white">📺 Canales</h1>
          <p className="text-white/40 text-sm mt-1">{mockChannelsData.length} canales configurados</p>
        </div>
        <Button variant="primary" icon={<FiPlus size={18} />} onClick={() => setShowModal(true)}>
          Agregar Canal
        </Button>
      </motion.div>

      <AdminTable
        columns={channelColumns}
        data={mockChannelsData}
        keyField="id"
        searchPlaceholder="Buscar canal..."
        actions={(item) => (
          <>
            <button onClick={() => toast.success('Editando: ' + item.name)} className="p-2 rounded-lg text-white/40 hover:text-accent hover:bg-accent/10 transition-all"><FiEdit2 size={15} /></button>
            <button onClick={() => toast.error('Eliminando: ' + item.name)} className="p-2 rounded-lg text-white/40 hover:text-red-400 hover:bg-red-400/10 transition-all"><FiTrash2 size={15} /></button>
          </>
        )}
      />

      <AdminModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        onSubmit={() => { toast.success('Canal creado'); setShowModal(false); }}
        title="Agregar Canal"
      >
        <div className="space-y-4">
          <Input label="Nombre del canal" placeholder="ESPN Deportes" value={newChannel.name} onChange={(e) => setNewChannel({ ...newChannel, name: e.target.value })} />
          <Input label="Número de canal" type="number" placeholder="1" value={newChannel.number} onChange={(e) => setNewChannel({ ...newChannel, number: e.target.value })} />
          <Input label="URL del Stream" placeholder="https://stream.example.com/live.m3u8" value={newChannel.streamUrl} onChange={(e) => setNewChannel({ ...newChannel, streamUrl: e.target.value })} />
          <Dropdown label="Categoría" options={categoryOptions} value={newChannel.categoryId} onChange={(v) => setNewChannel({ ...newChannel, categoryId: v })} />
          <div>
            <label className="block text-sm font-medium text-white/70 mb-1.5">Descripción</label>
            <textarea className="w-full bg-white/5 border border-white/10 rounded-lg px-4 py-3 text-white placeholder-white/30 focus:outline-none focus:border-primary/50 transition-all h-20 resize-none" placeholder="Descripción del canal..." value={newChannel.description} onChange={(e) => setNewChannel({ ...newChannel, description: e.target.value })} />
          </div>
        </div>
      </AdminModal>
    </div>
  );
}
