import { useState } from 'react'
import { Box, Typography, Button, CircularProgress } from '@mui/material'
import CreateCampaignForm from './CreateCampaignForm'
import CampaignCard from './CampaignCard'
import EditCampaignModal from './EditCampaignModal'
import { useCampaigns, useMediaCampaignIds } from './api'

export default function CampaignsPage() {
  const { data: campaigns, isLoading } = useCampaigns()
  const { data: mediaIds } = useMediaCampaignIds()
  const [showInactive, setShowInactive] = useState(false)
  const [editing, setEditing] = useState(null)

  const filtered = showInactive
    ? campaigns
    : campaigns?.filter((c) => c.active !== false)

  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
        <CircularProgress />
      </Box>
    )
  }

  return (
    <Box>
      <CreateCampaignForm />
      <Box sx={{ mt: 3 }}>
        <Box
          sx={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            mb: 2,
          }}
        >
          <Typography variant="h6">Lista de Campañas</Typography>
          <Button
            variant="outlined"
            size="small"
            onClick={() => setShowInactive((p) => !p)}
          >
            {showInactive ? 'Ocultar Inactivas' : 'Mostrar Inactivas'}
          </Button>
        </Box>
        {filtered?.map((c) => (
          <CampaignCard
            key={c.id}
            campaign={c}
            hasMedia={mediaIds?.has(c.id)}
            onEdit={() => setEditing(c)}
          />
        ))}
        {filtered?.length === 0 && (
          <Typography color="text.secondary">No se encontraron campañas.</Typography>
        )}
      </Box>
      <EditCampaignModal campaign={editing} onClose={() => setEditing(null)} />
    </Box>
  )
}
