"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { useConfirm } from "@/components/shared/use-confirm";

export function AnnouncementActions({
  announcementId,
  isActive,
}: {
  announcementId: number;
  isActive: boolean;
}) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const { confirm: askConfirm, dialog: confirmDialog } = useConfirm();

  async function toggleActive() {
    setLoading(true);
    try {
      const res = await fetch(`/api/admin/announcements/${announcementId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ is_active: !isActive }),
      });
      if (!res.ok) {
        alert("Failed to update announcement");
      } else {
        router.refresh();
      }
    } catch {
      alert("Failed to update announcement");
    } finally {
      setLoading(false);
    }
  }

  async function deleteAnnouncement() {
    if (!(await askConfirm({ title: "Delete announcement", message: "Are you sure you want to delete this announcement?" }))) return;
    setLoading(true);
    try {
      const res = await fetch(`/api/admin/announcements/${announcementId}`, {
        method: "DELETE",
      });
      if (!res.ok) {
        alert("Failed to delete announcement");
      } else {
        router.refresh();
      }
    } catch {
      alert("Failed to delete announcement");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex items-center gap-2">
      {confirmDialog}
      <button
        disabled={loading}
        onClick={toggleActive}
        className={`px-3 py-1 rounded text-xs disabled:opacity-50 ${
          isActive
            ? "bg-yellow-600 hover:bg-yellow-700 text-white"
            : "bg-green-600 hover:bg-green-700 text-white"
        }`}
      >
        {loading ? "..." : isActive ? "Deactivate" : "Activate"}
      </button>
      <button
        disabled={loading}
        onClick={deleteAnnouncement}
        className="bg-red-600 hover:bg-red-700 text-white px-3 py-1 rounded text-xs disabled:opacity-50"
      >
        Delete
      </button>
    </div>
  );
}

export function AnnouncementForm() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [type, setType] = useState("info");
  const [target, setTarget] = useState("all");
  const [expiresAt, setExpiresAt] = useState("");

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!title.trim() || !content.trim()) return;
    setLoading(true);
    try {
      const res = await fetch("/api/admin/announcements", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title: title.trim(),
          content: content.trim(),
          type,
          target,
          expires_at: expiresAt || null,
        }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        alert(data.error || "Failed to create announcement");
      } else {
        setTitle("");
        setContent("");
        setType("info");
        setTarget("all");
        setExpiresAt("");
        router.refresh();
      }
    } catch {
      alert("Failed to create announcement");
    } finally {
      setLoading(false);
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-text-muted text-sm mb-1">Title</label>
          <input
            type="text"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="Announcement title"
            className="w-full bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-text focus:outline-none focus:ring-1 focus:ring-primary"
            required
          />
        </div>
        <div className="flex gap-4">
          <div className="flex-1">
            <label className="block text-text-muted text-sm mb-1">Type</label>
            <select
              value={type}
              onChange={(e) => setType(e.target.value)}
              className="w-full bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-text focus:outline-none focus:ring-1 focus:ring-primary"
            >
              <option value="info">Info</option>
              <option value="warning">Warning</option>
              <option value="success">Success</option>
              <option value="urgent">Urgent</option>
            </select>
          </div>
          <div className="flex-1">
            <label className="block text-text-muted text-sm mb-1">Target</label>
            <select
              value={target}
              onChange={(e) => setTarget(e.target.value)}
              className="w-full bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-text focus:outline-none focus:ring-1 focus:ring-primary"
            >
              <option value="all">All</option>
              <option value="escorts">Escorts</option>
              <option value="clients">Clients</option>
              <option value="agencies">Agencies</option>
            </select>
          </div>
        </div>
      </div>
      <div>
        <label className="block text-text-muted text-sm mb-1">Content</label>
        <textarea
          value={content}
          onChange={(e) => setContent(e.target.value)}
          placeholder="Announcement content..."
          rows={3}
          className="w-full bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-text focus:outline-none focus:ring-1 focus:ring-primary"
          required
        />
      </div>
      <div className="flex items-end gap-4">
        <div>
          <label className="block text-text-muted text-sm mb-1">
            Expires (optional)
          </label>
          <input
            type="datetime-local"
            value={expiresAt}
            onChange={(e) => setExpiresAt(e.target.value)}
            className="bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-text focus:outline-none focus:ring-1 focus:ring-primary"
          />
        </div>
        <button
          type="submit"
          disabled={loading}
          className="bg-primary hover:bg-primary-dark text-white px-6 py-2 rounded-lg transition-colors text-sm disabled:opacity-50"
        >
          {loading ? "Creating..." : "Create Announcement"}
        </button>
      </div>
    </form>
  );
}
