import { useNavigate, useParams } from 'react-router-dom'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { MedioForm } from '../components/MedioForm'
import { useMedio } from '../hooks/useMedio'
import { useUpdateMedio } from '../hooks/useUpdateMedio'
import type { MedioFormValues } from '../components/MedioForm'

export function EditMedioPage() {
  const { id } = useParams<{ id: string }>()
  const medioId = Number(id)
  const navigate = useNavigate()

  const { data: medio, isLoading } = useMedio(medioId)
  const { mutate, isPending, error } = useUpdateMedio(medioId)

  function handleSubmit(values: MedioFormValues) {
    mutate(
      {
        nombre: values.nombre,
        tipo: values.tipo,
        plataformaEmpresaId: values.plataformaEmpresaId as number | null,
      },
      {
        onSuccess: () => {
          toast.success('Medio actualizado correctamente')
          void navigate(`/admin/medios/${medioId}`)
        },
      },
    )
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <span className="text-muted-foreground">Cargando...</span>
      </div>
    )
  }

  if (!medio) {
    return (
      <div className="py-12 text-center text-muted-foreground">
        Medio no encontrado.
      </div>
    )
  }

  return (
    <div className="flex justify-center py-8">
      <Card className="w-full max-w-lg">
        <CardHeader className="space-y-1">
          <div className="flex items-center justify-between">
            <CardTitle className="text-xl">Editar Medio</CardTitle>
            <Button variant="ghost" size="sm" onClick={() => navigate('/admin/medios')}>
              Volver
            </Button>
          </div>
          <CardDescription>
            Editá los datos del medio <strong>{medio.nombre}</strong>.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <MedioForm
            initialData={medio}
            isPending={isPending}
            error={error}
            onSubmit={handleSubmit}
          />
        </CardContent>
      </Card>
    </div>
  )
}
