// frontend/src/components/TablaTitulares.tsx

import { useState } from 'react';
import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Chip, IconButton, Typography, Link, TextField } from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import DragHandleIcon from '@mui/icons-material/DragHandle';
import EditIcon from '@mui/icons-material/Edit';
import { DndContext, closestCenter, PointerSensor, useSensor, useSensors, type DragEndEvent } from '@dnd-kit/core';
import { arrayMove, SortableContext, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import type { Titular } from '../types';
import type { ActualizarTitularPayload } from '../services/apiService';

interface SortableRowProps {
  titular: Titular;
  onDelete: (id: number) => void;
  onSave: (id: number, payload: ActualizarTitularPayload) => void;
  onEdit: (titular: Titular) => void;
}

const SortableRow = ({ titular, onDelete, onSave, onEdit }: SortableRowProps) => {
  const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: titular.id });
  const [isEditing, setIsEditing] = useState(false);
  const [editText, setEditText] = useState(titular.texto);

  const style = { transform: CSS.Transform.toString(transform), transition };

  const handleSave = () => {
    if (editText.trim() && editText.trim() !== titular.texto) {
      onSave(titular.id, { texto: editText.trim(), viñeta: titular.viñeta });
    }
    setIsEditing(false);
  };

  const getChipColor = (tipo: Titular['tipo']): "success" | "warning" | "info" => {
    if (tipo === 'Edited') return 'warning';
    if (tipo === 'Manual') return 'info';
    return 'success';
  };

  const formatFuente = (fuente: string | null) => {
    if (!fuente) return 'N/A';
    try {
      const url = new URL(fuente);
      return url.hostname.replace('www.', '');
    } catch {
      return fuente;
    }
  }

  return (
    <TableRow ref={setNodeRef} style={style} {...attributes} sx={{ '&:last-child td, &:last-child th': { border: 0 } }}>
      <TableCell sx={{ cursor: 'grab', verticalAlign: 'middle' }} {...listeners}>
        <DragHandleIcon sx={{ color: 'text.secondary' }} />
      </TableCell>
      <TableCell sx={{ verticalAlign: 'middle' }} onClick={() => setIsEditing(true)}>
        {isEditing ? (
          <TextField
            fullWidth
            autoFocus
            variant="standard"
            value={editText}
            onChange={(e) => setEditText(e.target.value)}
            onBlur={handleSave}
            onKeyDown={(e) => { if (e.key === 'Enter') handleSave(); }}
            onClick={(e) => e.stopPropagation()}
          />
        ) : (
          <Typography variant="body2">{titular.texto}</Typography>
        )}
      </TableCell>
      <TableCell sx={{ verticalAlign: 'middle' }}>
        <Chip label={titular.tipo || 'Scraped'} color={getChipColor(titular.tipo)} size="small" />
      </TableCell>
      <TableCell sx={{ verticalAlign: 'middle' }}>
        {titular.urlFuente ? (
          <Link href={titular.urlFuente} target="_blank" rel="noopener noreferrer" underline="hover" color="primary.light">
            {formatFuente(titular.fuente)}
          </Link>
        ) : (
          formatFuente(titular.fuente)
        )}
      </TableCell>
      <TableCell sx={{ verticalAlign: 'middle', textAlign: 'right' }}>
        <IconButton size="small" onClick={(e) => { e.stopPropagation(); onEdit(titular); }}>
          <EditIcon fontSize="small" />
        </IconButton>
        <IconButton size="small" onClick={(e) => { e.stopPropagation(); onDelete(titular.id); }} sx={{ color: '#ef4444' }}>
          <DeleteIcon />
        </IconButton>
      </TableCell>
    </TableRow>
  );
};

interface TablaTitularesProps {
  titulares: Titular[];
  onReorder: (titulares: Titular[]) => void;
  onDelete: (id: number) => void;
  onEdit: (titular: Titular) => void;
  onSave: (id: number, payload: ActualizarTitularPayload) => void;
}

const TablaTitulares = ({ titulares, onReorder, onDelete, onEdit, onSave }: TablaTitularesProps) => {
  const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }));

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    if (over && active.id !== over.id) {
      const oldIndex = titulares.findIndex((item) => item.id === active.id);
      const newIndex = titulares.findIndex((item) => item.id === over.id);
      onReorder(arrayMove(titulares, oldIndex, newIndex));
    }
  };

  if (titulares.length === 0) {
    return (
      <Paper elevation={0} sx={{ p: 3, textAlign: 'center' }}>
        <Typography>No hay titulares para mostrar.</Typography>
      </Paper>
    );
  }

  return (
    <Paper elevation={0} sx={{ overflow: 'hidden' }}>
      <TableContainer>
        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
          <SortableContext items={titulares.map(t => t.id)} strategy={verticalListSortingStrategy}>
            <Table>
              <TableHead>
                <TableRow sx={{ '& .MuiTableCell-root': { borderBottom: '1px solid rgba(255, 255, 255, 0.12)' } }}>
                  <TableCell sx={{ width: 50 }} />
                  <TableCell sx={{ textTransform: 'uppercase', color: 'text.secondary', letterSpacing: '0.05em' }}>Texto del Titular</TableCell>
                  <TableCell sx={{ textTransform: 'uppercase', color: 'text.secondary', letterSpacing: '0.05em' }}>Tipo</TableCell>
                  <TableCell sx={{ textTransform: 'uppercase', color: 'text.secondary', letterSpacing: '0.05em' }}>Fuente</TableCell>
                  <TableCell sx={{ textTransform: 'uppercase', color: 'text.secondary', letterSpacing: '0.05em', textAlign: 'right' }}>Acciones</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {titulares.map((titular) => (
                  <SortableRow key={titular.id} titular={titular} onDelete={onDelete} onEdit={onEdit} onSave={onSave} />
                ))}
              </TableBody>
            </Table>
          </SortableContext>
        </DndContext>
      </TableContainer>
    </Paper>
  );
};

export default TablaTitulares;