"use client";

import { useEffect, useState } from "react";
import { toast } from "sonner";

import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/shared/components/ui/dialog";
import { Button } from "@/shared/components/ui/button";
import { Input } from "@/shared/components/ui/input";
import { Label } from "@/shared/components/ui/label";
import { createContactListAction } from "../actions/create-contact-list-action";

type MarketingChannel = "EMAIL" | "SMS";

interface ListFormModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSaved: () => void;
}

export function ListFormModal({ open, onOpenChange, onSaved }: ListFormModalProps) {
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [marketingChannel, setMarketingChannel] = useState<MarketingChannel>("EMAIL");
  const [isSaving, setIsSaving] = useState(false);

  useEffect(() => {
    if (!open) return;
    setName("");
    setDescription("");
    setMarketingChannel("EMAIL");
  }, [open]);

  async function handleSubmit() {
    setIsSaving(true);
    try {
      await createContactListAction({ name, description: description || undefined, marketingChannel });
      toast.success("Lista criada.");
      onOpenChange(false);
      onSaved();
    } catch (err) {
      toast.error(err instanceof Error && err.message ? err.message : "Não foi possível criar a lista.");
    } finally {
      setIsSaving(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Adicionar uma Lista</DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          <div className="space-y-1.5">
            <Label htmlFor="list-name">Nome</Label>
            <Input id="list-name" value={name} onChange={(e) => setName(e.target.value)} placeholder="Ex: Newsletter Semanal" />
          </div>

          <div className="space-y-1.5">
            <Label htmlFor="list-description">Descrição</Label>
            <Input
              id="list-description"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Opcional"
            />
          </div>

          <div className="space-y-1.5">
            <Label htmlFor="list-channel">Canal de marketing</Label>
            <select
              id="list-channel"
              value={marketingChannel}
              onChange={(e) => setMarketingChannel(e.target.value as MarketingChannel)}
              className="w-full h-10 rounded-lg border border-zinc-300 bg-white px-2.5 text-sm"
            >
              <option value="EMAIL">Email</option>
              <option value="SMS">SMS</option>
            </select>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancelar
          </Button>
          <Button onClick={handleSubmit} disabled={isSaving || !name.trim()}>
            {isSaving ? "Salvando..." : "Salvar"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
