import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { toast } from "@/hooks/use-toast";
import { Plus, Trash2, Edit, Eye, EyeOff } from "lucide-react";
import { format } from "date-fns";

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? "";

interface Props {
  companyId: string;
}

const CompanyBlogTab = ({ companyId }: Props) => {
  const queryClient = useQueryClient();
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [form, setForm] = useState({ title: "", slug: "", content: "", image_url: "" });

  const { data: posts = [] } = useQuery({
    queryKey: ["tenant-posts", companyId],
    queryFn: async (): Promise<any[]> => {
      const res = await fetch(`/api/admin/companies/${companyId}/posts`);
      if (!res.ok) return [];
      return res.json();
    },
  });

  const saveMutation = useMutation({
    mutationFn: async () => {
      const slug = form.slug || form.title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
      const path = editing
        ? `/api/admin/companies/${companyId}/posts/${editing.id}`
        : `/api/admin/companies/${companyId}/posts`;
      const method = editing ? "PUT" : "POST";
      const res = await fetch(path, {
        method,
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
        body: JSON.stringify({
          company_id: companyId,
          title: form.title,
          slug,
          content: form.content,
          image_url: form.image_url || null,
        }),
      });
      if (!res.ok) throw new Error("Failed to save post");
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["tenant-posts", companyId] });
      setDialogOpen(false);
      setEditing(null);
      setForm({ title: "", slug: "", content: "", image_url: "" });
      toast({ title: editing ? "Post updated" : "Post created" });
    },
  });

  const togglePublish = useMutation({
    mutationFn: async (post: any) => {
      const res = await fetch(`/api/admin/companies/${companyId}/posts/${post.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
        body: JSON.stringify({
          published_at: post.published_at ? null : new Date().toISOString(),
        }),
      });
      if (!res.ok) throw new Error("Failed to toggle publish");
    },
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["tenant-posts", companyId] }),
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const res = await fetch(`/api/admin/companies/${companyId}/posts/${id}`, {
        method: "DELETE",
        headers: { "X-CSRF-TOKEN": csrfToken() },
      });
      if (!res.ok) throw new Error("Failed to delete post");
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["tenant-posts", companyId] });
      toast({ title: "Post deleted" });
    },
  });

  const openEdit = (post: any) => {
    setEditing(post);
    setForm({ title: post.title, slug: post.slug, content: post.content, image_url: post.image_url || "" });
    setDialogOpen(true);
  };

  const openNew = () => {
    setEditing(null);
    setForm({ title: "", slug: "", content: "", image_url: "" });
    setDialogOpen(true);
  };

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h3 className="text-lg font-semibold">Blog / News Posts</h3>
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogTrigger asChild>
            <Button size="sm" onClick={openNew}><Plus className="h-4 w-4 mr-1" /> New Post</Button>
          </DialogTrigger>
          <DialogContent className="max-w-lg">
            <DialogHeader>
              <DialogTitle>{editing ? "Edit Post" : "New Post"}</DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <Input placeholder="Title" value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} />
              <Input placeholder="Slug (auto-generated if empty)" value={form.slug} onChange={e => setForm({ ...form, slug: e.target.value })} />
              <Input placeholder="Image URL (optional)" value={form.image_url} onChange={e => setForm({ ...form, image_url: e.target.value })} />
              <Textarea placeholder="Content (markdown supported)" value={form.content} onChange={e => setForm({ ...form, content: e.target.value })} rows={8} />
              <Button onClick={() => saveMutation.mutate()} disabled={!form.title || saveMutation.isPending}>
                {editing ? "Update" : "Create"}
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {posts.length === 0 ? (
        <p className="text-sm text-muted-foreground">No posts yet.</p>
      ) : (
        <div className="space-y-2">
          {posts.map((post: any) => (
            <Card key={post.id}>
              <CardContent className="flex items-center justify-between p-4">
                <div>
                  <p className="font-medium text-sm">{post.title}</p>
                  <div className="flex items-center gap-2 mt-1">
                    <Badge variant={post.published_at ? "default" : "secondary"}>
                      {post.published_at ? "Published" : "Draft"}
                    </Badge>
                    {post.published_at && (
                      <span className="text-xs text-muted-foreground">
                        {format(new Date(post.published_at), "dd MMM yyyy")}
                      </span>
                    )}
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <Button variant="ghost" size="sm" onClick={() => togglePublish.mutate(post)}>
                    {post.published_at ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </Button>
                  <Button variant="ghost" size="sm" onClick={() => openEdit(post)}>
                    <Edit className="h-4 w-4" />
                  </Button>
                  <Button variant="ghost" size="sm" onClick={() => deleteMutation.mutate(post.id)}>
                    <Trash2 className="h-4 w-4 text-destructive" />
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
};

export default CompanyBlogTab;
