"use client";

import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Edit2, Loader2, Plus, Save, Star, Trash2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { adminApi, type TestimonialInput, type TestimonialResponse } from "@/lib/api";
import { getAdminToken } from "@/lib/admin-store";

const EMPTY_FORM: TestimonialInput = {
  name: "",
  role: "",
  content: "",
  rating: 5,
  avatar: "",
  sort_order: 0,
  is_active: true,
};

export default function AdminTestimonialsPage() {
  const router = useRouter();
  const [testimonials, setTestimonials] = useState<TestimonialResponse[]>([]);
  const [form, setForm] = useState<TestimonialInput>(EMPTY_FORM);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  const loadTestimonials = useCallback(async () => {
    const token = await getAdminToken();
    if (!token) {
      router.push("/admin-login");
      return;
    }
    setTestimonials(await adminApi.getTestimonials(token));
  }, [router]);

  useEffect(() => {
    (async () => {
      try {
        await loadTestimonials();
      } catch {
        router.push("/admin-login");
      } finally {
        setLoading(false);
      }
    })();
  }, [loadTestimonials, router]);

  const resetForm = () => {
    setForm(EMPTY_FORM);
    setEditingId(null);
    setError("");
  };

  const edit = (testimonial: TestimonialResponse) => {
    setEditingId(testimonial.id);
    setForm({
      name: testimonial.name,
      role: testimonial.role,
      content: testimonial.content,
      rating: testimonial.rating,
      avatar: testimonial.avatar,
      sort_order: testimonial.sort_order,
      is_active: testimonial.is_active,
    });
    setError("");
  };

  const save = async (event: React.FormEvent) => {
    event.preventDefault();
    const token = await getAdminToken();
    if (!token) return;

    setSaving(true);
    setError("");
    try {
      const payload = {
        ...form,
        rating: Math.min(5, Math.max(1, Number(form.rating) || 5)),
        sort_order: Number(form.sort_order) || 0,
        avatar: form.avatar?.trim() || undefined,
      };
      if (editingId) {
        const updated = await adminApi.updateTestimonial(token, editingId, payload);
        setTestimonials((prev) => prev.map((item) => (item.id === updated.id ? updated : item)));
      } else {
        const created = await adminApi.createTestimonial(token, payload);
        setTestimonials((prev) => [...prev, created]);
      }
      resetForm();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Could not save testimonial");
    } finally {
      setSaving(false);
    }
  };

  const remove = async (testimonialId: number) => {
    const token = await getAdminToken();
    if (!token) return;

    await adminApi.deleteTestimonial(token, testimonialId);
    setTestimonials((prev) => prev.filter((item) => item.id !== testimonialId));
    if (editingId === testimonialId) resetForm();
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20 text-zinc-500">
        <Loader2 className="w-5 h-5 animate-spin mr-2" /> Loading testimonials...
      </div>
    );
  }

  return (
    <div>
      <div className="mb-8 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Testimonials</h1>
          <p className="text-zinc-500 text-sm mt-1">Manage the creator quotes shown on the front page</p>
        </div>
        <Button onClick={resetForm} className="bg-white/5 border border-white/10 text-zinc-200 hover:bg-white/10">
          <Plus className="w-4 h-4 mr-2" /> New
        </Button>
      </div>

      <div className="grid xl:grid-cols-[minmax(0,1fr)_380px] gap-6">
        <div className="glass-card overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-white/8">
                  <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Creator</th>
                  <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Quote</th>
                  <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Rating</th>
                  <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Status</th>
                  <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Order</th>
                  <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Actions</th>
                </tr>
              </thead>
              <tbody>
                {testimonials.map((testimonial) => (
                  <tr key={testimonial.id} className="border-b border-white/5 hover:bg-white/3 transition-colors">
                    <td className="px-5 py-4">
                      <div className="flex items-center gap-3">
                        <div className="w-9 h-9 rounded-full bg-gradient-to-br from-violet-600 to-cyan-500 flex items-center justify-center text-sm font-bold text-white">
                          {testimonial.avatar}
                        </div>
                        <div>
                          <div className="text-sm font-medium text-white">{testimonial.name}</div>
                          <div className="text-xs text-zinc-500">{testimonial.role}</div>
                        </div>
                      </div>
                    </td>
                    <td className="px-5 py-4 text-sm text-zinc-400 max-w-sm">
                      <div className="line-clamp-2">{testimonial.content}</div>
                    </td>
                    <td className="px-5 py-4">
                      <div className="flex items-center gap-0.5">
                        {Array.from({ length: testimonial.rating }).map((_, index) => (
                          <Star key={index} className="w-3.5 h-3.5 fill-yellow-400 text-yellow-400" />
                        ))}
                      </div>
                    </td>
                    <td className="px-5 py-4">
                      <Badge
                        className={
                          testimonial.is_active
                            ? "bg-emerald-500/15 text-emerald-400 border-emerald-500/30 text-xs"
                            : "bg-zinc-800 text-zinc-400 border-zinc-700 text-xs"
                        }
                      >
                        {testimonial.is_active ? "active" : "hidden"}
                      </Badge>
                    </td>
                    <td className="px-5 py-4 text-sm text-zinc-400">{testimonial.sort_order}</td>
                    <td className="px-5 py-4">
                      <div className="flex items-center gap-1">
                        <Button
                          type="button"
                          size="sm"
                          variant="ghost"
                          className="h-8 px-2 text-zinc-400 hover:text-white"
                          onClick={() => edit(testimonial)}
                        >
                          <Edit2 className="w-3.5 h-3.5" />
                        </Button>
                        <Button
                          type="button"
                          size="sm"
                          variant="ghost"
                          className="h-8 px-2 text-red-400 hover:text-red-300"
                          onClick={() => remove(testimonial.id)}
                        >
                          <Trash2 className="w-3.5 h-3.5" />
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {testimonials.length === 0 && (
            <div className="p-8 text-center text-zinc-500 text-sm">No testimonials yet.</div>
          )}
        </div>

        <form onSubmit={save} className="glass-card p-6 h-fit">
          <div className="flex items-center justify-between mb-5">
            <h2 className="text-base font-semibold text-white">
              {editingId ? "Edit Testimonial" : "Add Testimonial"}
            </h2>
            {editingId && (
              <button type="button" onClick={resetForm} className="text-zinc-500 hover:text-zinc-300">
                <X className="w-4 h-4" />
              </button>
            )}
          </div>

          {error && (
            <div className="mb-4 text-xs text-red-400 p-3 rounded-lg bg-red-500/10 border border-red-500/20">
              {error}
            </div>
          )}

          <div className="space-y-4">
            <div className="space-y-1.5">
              <Label className="text-xs text-zinc-500">Name</Label>
              <Input
                required
                value={form.name}
                onChange={(e) => setForm((prev) => ({ ...prev, name: e.target.value }))}
                className="bg-white/5 border-white/10 text-white"
              />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs text-zinc-500">Role</Label>
              <Input
                required
                value={form.role}
                onChange={(e) => setForm((prev) => ({ ...prev, role: e.target.value }))}
                className="bg-white/5 border-white/10 text-white"
              />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs text-zinc-500">Quote</Label>
              <Textarea
                required
                value={form.content}
                onChange={(e) => setForm((prev) => ({ ...prev, content: e.target.value }))}
                className="min-h-28 bg-white/5 border-white/10 text-white"
              />
            </div>
            <div className="grid grid-cols-3 gap-3">
              <div className="space-y-1.5">
                <Label className="text-xs text-zinc-500">Rating</Label>
                <Input
                  type="number"
                  min={1}
                  max={5}
                  value={form.rating}
                  onChange={(e) => setForm((prev) => ({ ...prev, rating: Number(e.target.value) }))}
                  className="bg-white/5 border-white/10 text-white"
                />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs text-zinc-500">Avatar</Label>
                <Input
                  maxLength={10}
                  placeholder="RM"
                  value={form.avatar}
                  onChange={(e) => setForm((prev) => ({ ...prev, avatar: e.target.value.toUpperCase() }))}
                  className="bg-white/5 border-white/10 text-white"
                />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs text-zinc-500">Order</Label>
                <Input
                  type="number"
                  value={form.sort_order}
                  onChange={(e) => setForm((prev) => ({ ...prev, sort_order: Number(e.target.value) }))}
                  className="bg-white/5 border-white/10 text-white"
                />
              </div>
            </div>
            <div className="flex items-center justify-between rounded-lg border border-white/8 bg-white/[0.03] p-3">
              <div>
                <div className="text-sm text-white">Visible on front page</div>
                <div className="text-xs text-zinc-500">Hidden items remain saved for later</div>
              </div>
              <Switch
                checked={form.is_active}
                onCheckedChange={(checked) => setForm((prev) => ({ ...prev, is_active: checked }))}
                className="data-[state=checked]:bg-violet-600"
              />
            </div>
            <Button
              type="submit"
              disabled={saving}
              className="w-full bg-gradient-to-r from-violet-600 to-violet-500 text-white border-0"
            >
              {saving ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <Save className="w-4 h-4 mr-2" />}
              Save Testimonial
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}
