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 { Switch } from "@/components/ui/switch";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { toast } from "@/hooks/use-toast";
import { Plus, Trash2, Edit, Star } from "lucide-react";

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

interface Props {
  companyId: string;
}

const CompanyTestimonialsTab = ({ companyId }: Props) => {
  const queryClient = useQueryClient();
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [form, setForm] = useState({ author_name: "", author_role: "", content: "", rating: 5 });

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

  const saveMutation = useMutation({
    mutationFn: async () => {
      const path = editing
        ? `/api/admin/companies/${companyId}/testimonials/${editing.id}`
        : `/api/admin/companies/${companyId}/testimonials`;
      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,
          author_name: form.author_name,
          author_role: form.author_role || null,
          content: form.content,
          rating: form.rating,
        }),
      });
      if (!res.ok) throw new Error("Failed to save testimonial");
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["tenant-testimonials", companyId] });
      setDialogOpen(false);
      setEditing(null);
      setForm({ author_name: "", author_role: "", content: "", rating: 5 });
      toast({ title: editing ? "Testimonial updated" : "Testimonial added" });
    },
  });

  const toggleVisibility = useMutation({
    mutationFn: async ({ id, is_visible }: { id: string; is_visible: boolean }) => {
      const res = await fetch(`/api/admin/companies/${companyId}/testimonials/${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
        body: JSON.stringify({ is_visible }),
      });
      if (!res.ok) throw new Error("Failed to toggle visibility");
    },
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["tenant-testimonials", companyId] }),
  });

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

  const openEdit = (t: any) => {
    setEditing(t);
    setForm({ author_name: t.author_name, author_role: t.author_role || "", content: t.content, rating: t.rating });
    setDialogOpen(true);
  };

  const openNew = () => {
    setEditing(null);
    setForm({ author_name: "", author_role: "", content: "", rating: 5 });
    setDialogOpen(true);
  };

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h3 className="text-lg font-semibold">Testimonials</h3>
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogTrigger asChild>
            <Button size="sm" onClick={openNew}><Plus className="h-4 w-4 mr-1" /> Add Testimonial</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{editing ? "Edit Testimonial" : "Add Testimonial"}</DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <Input placeholder="Author name" value={form.author_name} onChange={e => setForm({ ...form, author_name: e.target.value })} />
              <Input placeholder="Role / Company (optional)" value={form.author_role} onChange={e => setForm({ ...form, author_role: e.target.value })} />
              <Textarea placeholder="Testimonial content" value={form.content} onChange={e => setForm({ ...form, content: e.target.value })} rows={4} />
              <div>
                <label className="text-sm font-medium mb-1 block">Rating</label>
                <div className="flex gap-1">
                  {[1, 2, 3, 4, 5].map(n => (
                    <button key={n} type="button" onClick={() => setForm({ ...form, rating: n })}>
                      <Star className={`h-5 w-5 ${n <= form.rating ? "text-yellow-500 fill-yellow-500" : "text-muted-foreground/30"}`} />
                    </button>
                  ))}
                </div>
              </div>
              <Button onClick={() => saveMutation.mutate()} disabled={!form.author_name || !form.content || saveMutation.isPending}>
                {editing ? "Update" : "Add"}
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {testimonials.length === 0 ? (
        <p className="text-sm text-muted-foreground">No testimonials yet.</p>
      ) : (
        <div className="space-y-2">
          {testimonials.map((t: any) => (
            <Card key={t.id}>
              <CardContent className="flex items-center justify-between p-4">
                <div>
                  <p className="font-medium text-sm">{t.author_name}</p>
                  <p className="text-xs text-muted-foreground">{t.author_role}</p>
                  <p className="text-sm text-muted-foreground mt-1 line-clamp-2">"{t.content}"</p>
                  <div className="flex gap-0.5 mt-1">
                    {[1, 2, 3, 4, 5].map(n => (
                      <Star key={n} className={`h-3 w-3 ${n <= t.rating ? "text-yellow-500 fill-yellow-500" : "text-muted-foreground/20"}`} />
                    ))}
                  </div>
                </div>
                <div className="flex items-center gap-2 shrink-0">
                  <div className="flex items-center gap-2">
                    <span className="text-xs text-muted-foreground">Visible</span>
                    <Switch checked={t.is_visible} onCheckedChange={(v) => toggleVisibility.mutate({ id: t.id, is_visible: v })} />
                  </div>
                  <Button variant="ghost" size="sm" onClick={() => openEdit(t)}>
                    <Edit className="h-4 w-4" />
                  </Button>
                  <Button variant="ghost" size="sm" onClick={() => deleteMutation.mutate(t.id)}>
                    <Trash2 className="h-4 w-4 text-destructive" />
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
};

export default CompanyTestimonialsTab;
