"use client";

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { adminDelete, adminGet, adminPatch, adminPost, adminPut } from "@/lib/api/admin-client";
import type {
  AdminBlogPost,
  AdminBlogPostDetail,
  AdminComment,
  AdminDemoRequest,
} from "@/lib/api/admin-types";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { notify } from "@/lib/notify";
import {
  CheckCircle2,
  XCircle,
  Trash2,
  Eye,
  EyeOff,
  Plus,
  ArrowLeft,
  Phone,
  Mail,
  Building2,
  Clock,
  MessageSquare,
} from "lucide-react";

// ── Blog Posts List ──────────────────────────────────────────────────────────

export function AdminBlogListScreen() {
  const t = useTranslations("admin.website");
  const qc = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ["admin", "website", "blog"],
    queryFn: () => adminGet<{ posts: AdminBlogPost[]; total: number }>("/api/admin/website/posts"),
  });

  const publishMut = useMutation({
    mutationFn: ({ id, publish }: { id: string; publish: boolean }) =>
      adminPatch(`/api/admin/website/posts/${id}/${publish ? "publish" : "unpublish"}`, {}),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["admin", "website", "blog"] });
      notify.success(t("saved"));
    },
    onError: () => notify.error(t("errorGeneric")),
  });

  const deleteMut = useMutation({
    mutationFn: (id: string) => adminDelete(`/api/admin/website/posts/${id}`),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["admin", "website", "blog"] });
      notify.success(t("deleted"));
    },
    onError: () => notify.error(t("errorGeneric")),
  });

  const posts = data?.posts ?? [];

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-lg font-medium">{t("blogTitle")}</h1>
        <a
          href="website/blog/new"
          className="inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90"
        >
          <Plus className="size-4" />
          {t("newPost")}
        </a>
      </div>

      {isLoading ? (
        <p className="text-sm text-muted-foreground">{t("loading")}</p>
      ) : posts.length === 0 ? (
        <Card className="rounded-xl border-dashed">
          <CardContent className="py-12 text-center text-sm text-muted-foreground">
            {t("noPosts")}
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-2">
          {posts.map((post) => (
            <Card key={post.id} className="rounded-xl border-border/80">
              <CardContent className="flex items-center gap-4 py-3">
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2">
                    <p className="truncate text-sm font-medium">{post.titleFa}</p>
                    {post.isPublished ? (
                      <Badge className="shrink-0 bg-green-100 text-green-800 hover:bg-green-100">
                        {t("published")}
                      </Badge>
                    ) : (
                      <Badge variant="secondary" className="shrink-0">
                        {t("draft")}
                      </Badge>
                    )}
                  </div>
                  <p className="mt-0.5 text-xs text-muted-foreground">
                    {post.slug} · {post.viewCount.toLocaleString("fa-IR")} {t("views")} ·{" "}
                    {post.commentCount.toLocaleString("fa-IR")} {t("commentsCount")}
                  </p>
                </div>
                <div className="flex shrink-0 items-center gap-1.5">
                  <Button
                    size="sm"
                    variant="ghost"
                    asChild
                    className="h-8 px-2 text-xs"
                  >
                    <a href={`website/blog/${post.id}`}>{t("edit")}</a>
                  </Button>
                  <Button
                    size="sm"
                    variant="ghost"
                    className="h-8 px-2 text-xs"
                    onClick={() => publishMut.mutate({ id: post.id, publish: !post.isPublished })}
                  >
                    {post.isPublished ? (
                      <EyeOff className="size-3.5" />
                    ) : (
                      <Eye className="size-3.5" />
                    )}
                  </Button>
                  <Button
                    size="sm"
                    variant="ghost"
                    className="h-8 px-2 text-xs text-destructive hover:text-destructive"
                    onClick={() => deleteMut.mutate(post.id)}
                  >
                    <Trash2 className="size-3.5" />
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}

// ── Blog Post Editor ─────────────────────────────────────────────────────────

interface PostEditorProps {
  postId?: string; // undefined = new post
}

export function AdminBlogEditorScreen({ postId }: PostEditorProps) {
  const t = useTranslations("admin.website");
  const qc = useQueryClient();
  const isNew = !postId;

  const { data: post } = useQuery({
    queryKey: ["admin", "website", "blog", postId],
    queryFn: () => adminGet<AdminBlogPostDetail>(`/api/admin/website/posts/${postId}`),
    enabled: !isNew,
  });

  const [form, setForm] = useState({
    slug: "",
    titleFa: "",
    titleEn: "",
    excerptFa: "",
    excerptEn: "",
    contentFa: "",
    contentEn: "",
    author: "تیم میزی",
    categoryFa: "",
    categoryEn: "",
  });

  // Sync fetched data into form once loaded
  const initialised = !isNew && post;
  const displayForm = initialised
    ? {
        slug: post!.slug,
        titleFa: post!.titleFa,
        titleEn: post!.titleEn,
        excerptFa: post!.excerptFa,
        excerptEn: post!.excerptEn,
        contentFa: post!.contentFa,
        contentEn: post!.contentEn,
        author: post!.author,
        categoryFa: post!.categoryFa,
        categoryEn: post!.categoryEn,
      }
    : form;

  const saveMut = useMutation({
    mutationFn: (data: typeof form) =>
      isNew
        ? adminPost("/api/admin/website/posts", data)
        : adminPut(`/api/admin/website/posts/${postId}`, data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["admin", "website", "blog"] });
      notify.success(t("saved"));
    },
    onError: () => notify.error(t("errorGeneric")),
  });

  const Field = ({
    label,
    value,
    onChange,
    multiline,
  }: {
    label: string;
    value: string;
    onChange: (v: string) => void;
    multiline?: boolean;
  }) => (
    <div>
      <label className="mb-1 block text-xs font-medium text-muted-foreground">{label}</label>
      {multiline ? (
        <textarea
          rows={8}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className="w-full resize-y rounded-lg border border-border bg-background px-3 py-2 font-mono text-xs outline-none focus:ring-2 focus:ring-primary/30"
          dir={label.toLowerCase().includes("fa") || label.includes("فارسی") ? "rtl" : "ltr"}
        />
      ) : (
        <Input
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className="h-9 text-sm"
          dir={label.toLowerCase().includes("fa") || label.includes("فارسی") ? "rtl" : "ltr"}
        />
      )}
    </div>
  );

  const current = initialised ? post! : form;
  const setField = (key: keyof typeof form) => (v: string) => {
    if (initialised) {
      // We'd need local state override — keep it simple for demo
    }
    setForm((f) => ({ ...f, [key]: v }));
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        <Button variant="ghost" size="sm" asChild>
          <a href="." className="flex items-center gap-1.5">
            <ArrowLeft className="size-4" />
            {t("backToBlog")}
          </a>
        </Button>
        <h1 className="text-lg font-medium">
          {isNew ? t("newPost") : t("editPost")}
        </h1>
      </div>

      <Card className="rounded-xl border-border/80">
        <CardContent className="space-y-4 pt-5">
          <div className="grid gap-4 sm:grid-cols-2">
            <Field
              label={t("fieldSlug")}
              value={isNew ? form.slug : (post?.slug ?? "")}
              onChange={setField("slug")}
            />
            <Field
              label={t("fieldAuthor")}
              value={isNew ? form.author : (post?.author ?? "")}
              onChange={setField("author")}
            />
          </div>
          <div className="grid gap-4 sm:grid-cols-2">
            <Field
              label={t("fieldTitleFa")}
              value={isNew ? form.titleFa : (post?.titleFa ?? "")}
              onChange={setField("titleFa")}
            />
            <Field
              label={t("fieldTitleEn")}
              value={isNew ? form.titleEn : (post?.titleEn ?? "")}
              onChange={setField("titleEn")}
            />
          </div>
          <div className="grid gap-4 sm:grid-cols-2">
            <Field
              label={t("fieldExcerptFa")}
              value={isNew ? form.excerptFa : (post?.excerptFa ?? "")}
              onChange={setField("excerptFa")}
            />
            <Field
              label={t("fieldExcerptEn")}
              value={isNew ? form.excerptEn : (post?.excerptEn ?? "")}
              onChange={setField("excerptEn")}
            />
          </div>
          <div className="grid gap-4 sm:grid-cols-2">
            <Field
              label={t("fieldCategoryFa")}
              value={isNew ? form.categoryFa : (post?.categoryFa ?? "")}
              onChange={setField("categoryFa")}
            />
            <Field
              label={t("fieldCategoryEn")}
              value={isNew ? form.categoryEn : (post?.categoryEn ?? "")}
              onChange={setField("categoryEn")}
            />
          </div>
          <Field
            label={t("fieldContentFa")}
            value={isNew ? form.contentFa : (post?.contentFa ?? "")}
            onChange={setField("contentFa")}
            multiline
          />
          <Field
            label={t("fieldContentEn")}
            value={isNew ? form.contentEn : (post?.contentEn ?? "")}
            onChange={setField("contentEn")}
            multiline
          />

          <div className="flex justify-end pt-2">
            <Button
              onClick={() => saveMut.mutate(isNew ? form : {
                slug: post?.slug ?? form.slug,
                titleFa: post?.titleFa ?? form.titleFa,
                titleEn: post?.titleEn ?? form.titleEn,
                excerptFa: post?.excerptFa ?? form.excerptFa,
                excerptEn: post?.excerptEn ?? form.excerptEn,
                contentFa: post?.contentFa ?? form.contentFa,
                contentEn: post?.contentEn ?? form.contentEn,
                author: post?.author ?? form.author,
                categoryFa: post?.categoryFa ?? form.categoryFa,
                categoryEn: post?.categoryEn ?? form.categoryEn,
              })}
              disabled={saveMut.isPending}
              className="min-w-[100px]"
            >
              {saveMut.isPending ? t("saving") : t("save")}
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

// ── Comments Moderation ──────────────────────────────────────────────────────

export function AdminCommentsScreen() {
  const t = useTranslations("admin.website");
  const qc = useQueryClient();
  const [filter, setFilter] = useState<"all" | "pending" | "approved">("pending");

  const approvedParam =
    filter === "pending" ? "approved=false" : filter === "approved" ? "approved=true" : "";

  const { data, isLoading } = useQuery({
    queryKey: ["admin", "website", "comments", filter],
    queryFn: () =>
      adminGet<{ comments: AdminComment[]; total: number }>(
        `/api/admin/website/comments${approvedParam ? `?${approvedParam}` : ""}`
      ),
  });

  const approveMut = useMutation({
    mutationFn: (id: string) => adminPatch(`/api/admin/website/comments/${id}/approve`, {}),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["admin", "website", "comments"] });
      notify.success(t("commentApproved"));
    },
    onError: () => notify.error(t("errorGeneric")),
  });

  const rejectMut = useMutation({
    mutationFn: (id: string) => adminDelete(`/api/admin/website/comments/${id}`),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["admin", "website", "comments"] });
      notify.success(t("commentDeleted"));
    },
    onError: () => notify.error(t("errorGeneric")),
  });

  const comments = data?.comments ?? [];

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-lg font-medium">{t("commentsTitle")}</h1>
        <div className="flex gap-1">
          {(["all", "pending", "approved"] as const).map((f) => (
            <Button
              key={f}
              size="sm"
              variant={filter === f ? "default" : "outline"}
              className="h-8 text-xs"
              onClick={() => setFilter(f)}
            >
              {t(`filterComment_${f}`)}
            </Button>
          ))}
        </div>
      </div>

      {isLoading ? (
        <p className="text-sm text-muted-foreground">{t("loading")}</p>
      ) : comments.length === 0 ? (
        <Card className="rounded-xl border-dashed">
          <CardContent className="py-12 text-center text-sm text-muted-foreground">
            {t("noComments")}
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-2">
          {comments.map((c) => (
            <Card key={c.id} className="rounded-xl border-border/80">
              <CardContent className="py-3">
                <div className="flex items-start gap-3">
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium">{c.authorName}</span>
                      {c.authorEmail && (
                        <span className="text-xs text-muted-foreground">{c.authorEmail}</span>
                      )}
                      {c.isApproved ? (
                        <Badge className="shrink-0 bg-green-100 text-green-800 hover:bg-green-100 text-[10px]">
                          {t("approved")}
                        </Badge>
                      ) : (
                        <Badge variant="secondary" className="shrink-0 text-[10px]">
                          {t("pending")}
                        </Badge>
                      )}
                    </div>
                    <p className="mt-0.5 text-xs text-muted-foreground">
                      {t("postSlug")}: {c.postSlug} ·{" "}
                      {new Date(c.createdAt).toLocaleDateString("fa-IR")}
                    </p>
                    <p className="mt-2 rounded-lg bg-muted/40 p-2 text-sm leading-relaxed">
                      {c.content}
                    </p>
                  </div>
                  <div className="flex shrink-0 flex-col gap-1.5">
                    {!c.isApproved && (
                      <Button
                        size="sm"
                        variant="ghost"
                        className="h-8 px-2 text-green-700 hover:text-green-800"
                        onClick={() => approveMut.mutate(c.id)}
                      >
                        <CheckCircle2 className="size-4" />
                      </Button>
                    )}
                    <Button
                      size="sm"
                      variant="ghost"
                      className="h-8 px-2 text-destructive hover:text-destructive"
                      onClick={() => rejectMut.mutate(c.id)}
                    >
                      <Trash2 className="size-4" />
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}

// ── Demo Requests ────────────────────────────────────────────────────────────

const STATUS_COLORS: Record<string, string> = {
  New: "bg-blue-100 text-blue-800",
  Contacted: "bg-yellow-100 text-yellow-800",
  DemoScheduled: "bg-purple-100 text-purple-800",
  Converted: "bg-green-100 text-green-800",
  Rejected: "bg-red-100 text-red-800",
};

export function AdminDemoRequestsScreen() {
  const t = useTranslations("admin.website");
  const qc = useQueryClient();
  const [statusFilter, setStatusFilter] = useState("");

  const { data, isLoading } = useQuery({
    queryKey: ["admin", "website", "demo-requests", statusFilter],
    queryFn: () =>
      adminGet<{ requests: AdminDemoRequest[]; total: number }>(
        `/api/admin/website/demo-requests${statusFilter ? `?status=${statusFilter}` : ""}`
      ),
  });

  const updateStatusMut = useMutation({
    mutationFn: ({ id, status, adminNotes }: { id: string; status: string; adminNotes?: string }) =>
      adminPatch(`/api/admin/website/demo-requests/${id}/status`, { status, adminNotes }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["admin", "website", "demo-requests"] });
      notify.success(t("saved"));
    },
    onError: () => notify.error(t("errorGeneric")),
  });

  const requests = data?.requests ?? [];
  const statuses = ["", "New", "Contacted", "DemoScheduled", "Converted", "Rejected"];

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-lg font-medium">{t("demoRequestsTitle")}</h1>
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="rounded-lg border border-border bg-background px-3 py-1.5 text-sm"
        >
          {statuses.map((s) => (
            <option key={s} value={s}>
              {s ? t(`demoStatus_${s}`) : t("allStatuses")}
            </option>
          ))}
        </select>
      </div>

      {isLoading ? (
        <p className="text-sm text-muted-foreground">{t("loading")}</p>
      ) : requests.length === 0 ? (
        <Card className="rounded-xl border-dashed">
          <CardContent className="py-12 text-center text-sm text-muted-foreground">
            {t("noDemoRequests")}
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-2">
          {requests.map((req) => (
            <Card key={req.id} className="rounded-xl border-border/80">
              <CardContent className="py-4">
                <div className="flex flex-wrap items-start gap-4">
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <span className="font-medium">{req.contactName}</span>
                      <Badge
                        className={`shrink-0 text-[10px] ${STATUS_COLORS[req.status] ?? ""} hover:opacity-80`}
                      >
                        {t(`demoStatus_${req.status}`)}
                      </Badge>
                    </div>
                    <div className="mt-1 flex flex-wrap gap-3 text-xs text-muted-foreground">
                      <span className="flex items-center gap-1">
                        <Building2 className="size-3" />
                        {req.businessName}
                      </span>
                      <span className="flex items-center gap-1">
                        <Phone className="size-3" />
                        {req.phone}
                      </span>
                      {req.email && (
                        <span className="flex items-center gap-1">
                          <Mail className="size-3" />
                          {req.email}
                        </span>
                      )}
                      <span className="flex items-center gap-1">
                        <Clock className="size-3" />
                        {new Date(req.createdAt).toLocaleDateString("fa-IR")}
                      </span>
                    </div>
                    {req.notes && (
                      <p className="mt-2 rounded-lg bg-muted/40 p-2 text-xs">{req.notes}</p>
                    )}
                  </div>
                  <div className="shrink-0">
                    <select
                      value={req.status}
                      onChange={(e) =>
                        updateStatusMut.mutate({ id: req.id, status: e.target.value })
                      }
                      className="rounded-lg border border-border bg-background px-2 py-1 text-xs"
                    >
                      {["New", "Contacted", "DemoScheduled", "Converted", "Rejected"].map((s) => (
                        <option key={s} value={s}>
                          {t(`demoStatus_${s}`)}
                        </option>
                      ))}
                    </select>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
