'use client';

import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { FiPlus, FiEdit2, FiTrash2, FiStar } from 'react-icons/fi';
import CategoryTabs from '@/components/content/CategoryTabs';
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 { formatDateShort, formatRating, formatDuration } from '@/lib/utils';
import toast from 'react-hot-toast';
import type { TableColumn } from '@/types';

const contentTabs = [
  { id: 'movies', name: '🎬 Películas' },
  { id: 'series', name: '📺 Series' },
];

interface MovieRow { id: string; title: string; year: number; duration: number; rating: number; genres: string; quality: string; views: number; addedAt: string; [key: string]: unknown; }
interface SeriesRow { id: string; title: string; year: number; seasons: number; episodes: number; rating: number; genres: string; status: string; views: number; addedAt: string; [key: string]: unknown; }

const mockMoviesData: MovieRow[] = [
  { id: 'm1', title: 'El Último Horizonte', year: 2024, duration: 142, rating: 8.7, genres: 'Acción, Sci-Fi', quality: '4K', views: 45230, addedAt: '2024-01-15T00:00:00Z' },
  { id: 'm2', title: 'Noches de Cristal', year: 2024, duration: 128, rating: 8.3, genres: 'Thriller', quality: '1080p', views: 32100, addedAt: '2024-02-20T00:00:00Z' },
  { id: 'm3', title: 'Tormenta de Fuego', year: 2024, duration: 125, rating: 8.2, genres: 'Acción', quality: '4K', views: 34500, addedAt: '2024-01-05T00:00:00Z' },
  { id: 'm4', title: 'Amor en Venecia', year: 2023, duration: 110, rating: 7.6, genres: 'Romance', quality: '1080p', views: 28900, addedAt: '2023-10-15T00:00:00Z' },
  { id: 'm5', title: 'El Protocolo', year: 2024, duration: 138, rating: 8.5, genres: 'Thriller', quality: '4K', views: 41200, addedAt: '2024-02-28T00:00:00Z' },
  { id: 'm6', title: 'Cuentos de Luna', year: 2024, duration: 95, rating: 8.8, genres: 'Animación', quality: '4K', views: 52100, addedAt: '2024-03-15T00:00:00Z' },
  { id: 'm7', title: 'Ecos del Abismo', year: 2023, duration: 108, rating: 7.4, genres: 'Horror', quality: '720p', views: 16400, addedAt: '2023-10-31T00:00:00Z' },
];

const mockSeriesData: SeriesRow[] = [
  { id: 's1', title: 'Los Herederos', year: 2023, seasons: 3, episodes: 30, rating: 9.0, genres: 'Drama', status: 'ongoing', views: 89000, addedAt: '2023-06-01T00:00:00Z' },
  { id: 's2', title: 'Código Negro', year: 2024, seasons: 2, episodes: 16, rating: 8.7, genres: 'Thriller', status: 'ongoing', views: 67500, addedAt: '2024-01-10T00:00:00Z' },
  { id: 's3', title: 'Mundos Paralelos', year: 2023, seasons: 2, episodes: 20, rating: 8.4, genres: 'Sci-Fi', status: 'ongoing', views: 45200, addedAt: '2023-09-15T00:00:00Z' },
  { id: 's4', title: 'La Corona Dorada', year: 2022, seasons: 4, episodes: 40, rating: 9.2, genres: 'Drama', status: 'ended', views: 102000, addedAt: '2022-03-20T00:00:00Z' },
  { id: 's5', title: 'Reinos Olvidados', year: 2023, seasons: 2, episodes: 18, rating: 8.9, genres: 'Fantasía', status: 'ongoing', views: 56700, addedAt: '2023-07-12T00:00:00Z' },
];

const movieColumns: TableColumn<MovieRow>[] = [
  { key: 'title', label: 'Título', sortable: true },
  { key: 'year', label: 'Año', sortable: true },
  { key: 'duration', label: 'Duración', render: (item) => <span>{formatDuration(item.duration)}</span> },
  { key: 'rating', label: 'Rating', sortable: true, render: (item) => (
    <span className="flex items-center gap-1 text-yellow-400"><FiStar size={12} className="fill-yellow-400" />{formatRating(item.rating)}</span>
  ) },
  { key: 'genres', label: 'Género' },
  { key: 'quality', label: 'Calidad', render: (item) => <Badge variant="accent" size="sm">{item.quality}</Badge> },
  { key: 'views', label: 'Vistas', sortable: true, render: (item) => <span className="text-white/50">{item.views.toLocaleString()}</span> },
  { key: 'addedAt', label: 'Agregado', sortable: true, render: (item) => <span className="text-white/50 text-xs">{formatDateShort(item.addedAt)}</span> },
];

const seriesColumns: TableColumn<SeriesRow>[] = [
  { key: 'title', label: 'Título', sortable: true },
  { key: 'year', label: 'Año', sortable: true },
  { key: 'seasons', label: 'Temp.' },
  { key: 'episodes', label: 'Ep.' },
  { key: 'rating', label: 'Rating', sortable: true, render: (item) => (
    <span className="flex items-center gap-1 text-yellow-400"><FiStar size={12} className="fill-yellow-400" />{formatRating(item.rating)}</span>
  ) },
  { key: 'genres', label: 'Género' },
  { key: 'status', label: 'Estado', render: (item) => (
    <Badge variant={item.status === 'ongoing' ? 'success' : item.status === 'ended' ? 'neutral' : 'danger'} size="sm">
      {item.status === 'ongoing' ? 'En emisión' : item.status === 'ended' ? 'Finalizada' : 'Cancelada'}
    </Badge>
  ) },
  { key: 'views', label: 'Vistas', sortable: true, render: (item) => <span className="text-white/50">{item.views.toLocaleString()}</span> },
];

export default function AdminContentPage() {
  const [activeTab, setActiveTab] = useState('movies');
  const [showModal, setShowModal] = useState(false);

  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">🎬 Contenido</h1>
          <p className="text-white/40 text-sm mt-1">Gestiona películas y series</p>
        </div>
        <Button variant="primary" icon={<FiPlus size={18} />} onClick={() => setShowModal(true)}>
          {activeTab === 'movies' ? 'Agregar Película' : 'Agregar Serie'}
        </Button>
      </motion.div>

      <CategoryTabs categories={contentTabs} activeCategory={activeTab} onChange={setActiveTab} />

      {activeTab === 'movies' ? (
        <AdminTable
          columns={movieColumns}
          data={mockMoviesData}
          keyField="id"
          searchPlaceholder="Buscar película..."
          actions={(item) => (
            <>
              <button onClick={() => toast.success('Editando: ' + item.title)} 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.title)} className="p-2 rounded-lg text-white/40 hover:text-red-400 hover:bg-red-400/10 transition-all"><FiTrash2 size={15} /></button>
            </>
          )}
        />
      ) : (
        <AdminTable
          columns={seriesColumns}
          data={mockSeriesData}
          keyField="id"
          searchPlaceholder="Buscar serie..."
          actions={(item) => (
            <>
              <button onClick={() => toast.success('Editando: ' + item.title)} 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.title)} 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('Contenido guardado'); setShowModal(false); }}
        title={activeTab === 'movies' ? 'Agregar Película' : 'Agregar Serie'}
        size="lg"
      >
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <Input label="Título" placeholder="Nombre del contenido" />
          <Input label="Año" type="number" placeholder="2024" />
          {activeTab === 'movies' && <Input label="Duración (min)" type="number" placeholder="120" />}
          <Input label="Rating" type="number" placeholder="8.5" />
          <Input label="Géneros" placeholder="Acción, Drama" className="md:col-span-2" />
          <Input label="URL del Poster" placeholder="https://..." />
          <Input label="URL del Backdrop" placeholder="https://..." />
          <Input label="URL del Stream" placeholder="https://..." className="md:col-span-2" />
          <div className="md:col-span-2">
            <label className="block text-sm font-medium text-white/70 mb-1.5">Sinopsis</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 focus:ring-1 focus:ring-primary/30 transition-all h-24 resize-none" placeholder="Descripción del contenido..." />
          </div>
        </div>
      </AdminModal>
    </div>
  );
}
