import {
  createHelpPage,
  deleteHelpPage,
  getAllHelpPage,
  getDetailHelpPage,
  updateHelpPage,
} from "@/pages/site-page/lib/api";
import { Button } from "@/shared/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/ui/card";
import { Checkbox } from "@/shared/ui/checkbox";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogTitle,
  DialogTrigger,
} from "@/shared/ui/dialog";
import { Input } from "@/shared/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/ui/select";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Edit2, Trash2 } from "lucide-react";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import ReactQuill from "react-quill-new";
import "react-quill-new/dist/quill.snow.css";
import { toast } from "sonner";

export default function PolicyCrud() {
  const { t } = useTranslation();
  const [deleteOpen, setDeleteOpen] = useState<boolean>(false);
  const queryClient = useQueryClient();
  const { data: items } = useQuery({
    queryKey: ["help_page"],
    queryFn: () => {
      return getAllHelpPage({ page: 1, page_size: 99 });
    },
    select(data) {
      return data.data.data.results;
    },
  });

  const { data: PrivacyPolicy } = useQuery({
    queryKey: ["privacy_policy"],
    queryFn: () => {
      return getAllHelpPage({
        page: 1,
        page_size: 99,
        page_type: "privacy_policy",
      });
    },
    select(data) {
      return data.data.data;
    },
  });

  const { data: UserAgreement } = useQuery({
    queryKey: ["user_agreement"],
    queryFn: () => {
      return getAllHelpPage({
        page: 1,
        page_size: 99,
        page_type: "user_agreement",
      });
    },
    select(data) {
      return data.data.data;
    },
  });

  const [editing, setEditing] = useState<number | null>(null);

  const { data: detail } = useQuery({
    queryKey: ["help_page_detail", editing],
    queryFn: () => {
      return getDetailHelpPage(editing!);
    },
    select(data) {
      return data.data.data;
    },
    enabled: !!editing,
  });

  const [form, setForm] = useState<{
    title: string;
    title_ru: string;
    content_ru: string;
    content: string;
    page_type: "privacy_policy" | "user_agreement";
    is_active: boolean;
  }>({
    title: "",
    content_ru: "",
    title_ru: "",
    content: "",
    page_type: "privacy_policy",
    is_active: true,
  });

  const [errors, setErrors] = useState<Record<string, string>>({});

  const { mutate: create } = useMutation({
    mutationFn: ({
      body,
    }: {
      body: {
        title: string;
        title_ru: string;
        content_ru: string;
        content: string;
        page_type: "privacy_policy" | "user_agreement";
        is_active: boolean;
      };
    }) => createHelpPage({ body }),
    onSuccess: () => {
      resetForm();
      queryClient.refetchQueries({ queryKey: ["help_page"] });
      queryClient.refetchQueries({ queryKey: ["help_page_detail"] });
      queryClient.refetchQueries({ queryKey: ["privacy_policy"] });
      queryClient.refetchQueries({ queryKey: ["user_agreement"] });
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        position: "top-center",
        richColors: true,
      });
    },
  });

  const { mutate: update } = useMutation({
    mutationFn: ({
      body,
      id,
    }: {
      id: number;
      body: {
        title: string;
        title_ru: string;
        content_ru: string;
        content: string;
        page_type?: "privacy_policy" | "user_agreement";
        is_active?: boolean;
      };
    }) => updateHelpPage({ body, id }),
    onSuccess: () => {
      resetForm();
      queryClient.refetchQueries({ queryKey: ["help_page"] });
      queryClient.refetchQueries({ queryKey: ["help_page_detail"] });
      queryClient.refetchQueries({ queryKey: ["privacy_policy"] });
      queryClient.refetchQueries({ queryKey: ["user_agreement"] });
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        position: "top-center",
        richColors: true,
      });
    },
  });

  const { mutate: deleteHelp } = useMutation({
    mutationFn: (id: number) => deleteHelpPage(id),
    onSuccess: () => {
      resetForm();
      queryClient.refetchQueries({ queryKey: ["help_page"] });
      queryClient.refetchQueries({ queryKey: ["help_page_detail"] });
      queryClient.refetchQueries({ queryKey: ["privacy_policy"] });
      queryClient.refetchQueries({ queryKey: ["user_agreement"] });
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        position: "top-center",
        richColors: true,
      });
    },
  });

  function resetForm() {
    setForm({
      title: "",
      title_ru: "",
      content_ru: "",
      content: "",
      is_active: true,
      page_type: "privacy_policy",
    });
    setErrors({});
    setEditing(null);
  }

  useEffect(() => {
    if (detail && editing) {
      setForm({
        content: detail.content,
        is_active: detail.is_active,
        page_type: detail.page_type,
        title: detail.title,
        content_ru: detail.content_ru,
        title_ru: detail.title_ru,
      });
    }
  }, [detail, editing]);

  function validate(
    f: Partial<{
      title: string;
      content: string;
      page_type: "privacy_policy" | "user_agreement";
      is_active: boolean;
    }>,
  ) {
    const e: Record<string, string> = {};
    if (!f.title || f.title.trim().length < 3)
      e.title = "Sarlavha kamida 3 ta belgidan iborat bo'lishi kerak";
    if (!f.content || f.content.trim().length < 10)
      e.content = "Kontent kamida 10 ta belgidan iborat bo'lishi kerak";
    return e;
  }

  function handleCreateOrUpdate() {
    const validation = validate(form);
    if (Object.keys(validation).length) {
      setErrors(validation);
      return;
    }

    if (editing) {
      update({
        body: {
          content: form.content,
          is_active: form.is_active,
          page_type: form.page_type,
          title: form.title,
          content_ru: form.content_ru,
          title_ru: form.title_ru,
        },
        id: editing,
      });
    } else {
      create({
        body: {
          content: form.content,
          is_active: form.is_active,
          page_type: form.page_type,
          title: form.title,
          content_ru: form.content_ru,
          title_ru: form.title_ru,
        },
      });
    }
  }

  function startEdit(item: number) {
    setEditing(item);
  }

  function removeItem(id: number) {
    deleteHelp(id);
  }

  const individualExists = !!PrivacyPolicy?.results?.length;
  const legalExists = !!UserAgreement?.results?.length;

  const isAddDisabled =
    !editing &&
    ((form.page_type === "privacy_policy" && individualExists) ||
      (form.page_type === "user_agreement" && legalExists));

  return (
    <div className="min-h-screen w-full p-6 bg-gray-900">
      <div className="max-w-[90%] mx-auto space-y-6">
        <div className="flex items-center justify-between">
          <h1 className="text-3xl font-bold">
            {t("Yordam sahifalari boshqaruvi")}
          </h1>
        </div>

        <Card className="bg-gray-900">
          <CardHeader>
            <CardTitle>
              {editing ? t("Tahrirlash") : t("Yangi yordam sahifasi yaratish")}
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <label className="text-sm font-medium">{t("Sarlavha")}</label>
              <Input
                value={form.title || ""}
                onChange={(e) =>
                  setForm((s) => ({ ...s, title: e.target.value }))
                }
                placeholder={t("Yordam sahifasi sarlavhasi")}
                className="mt-1"
              />
              {errors.title && (
                <p className="text-destructive text-sm mt-1">
                  {t(errors.title)}
                </p>
              )}
            </div>

            <div>
              <label className="text-sm font-medium">
                {t("Sarlavha")} (ru)
              </label>
              <Input
                value={form.title_ru || ""}
                onChange={(e) =>
                  setForm((s) => ({ ...s, title_ru: e.target.value }))
                }
                placeholder={t("Yordam sahifasi sarlavhasi") + " (ru)"}
                className="mt-1"
              />
              {errors.title && (
                <p className="text-destructive text-sm mt-1">
                  {t(errors.title)}
                </p>
              )}
            </div>

            <div className="h-[280px] w-[100%]">
              <label className="text-sm font-medium">{t("Kontent")}</label>
              <div className="mt-1">
                <ReactQuill
                  value={form.content || ""}
                  onChange={(value) =>
                    setForm((s) => ({ ...s, content: value }))
                  }
                  className="bg-gray-900 h-48"
                  placeholder={t("Yordam matnini kiriting...")}
                />
              </div>
              {errors.content && (
                <p className="text-destructive text-sm mt-12">
                  {t(errors.content)}
                </p>
              )}
            </div>

            <div className="h-[280px] w-[100%]">
              <label className="text-sm font-medium">{t("Kontent")} (ru)</label>
              <div className="mt-1">
                <ReactQuill
                  value={form.content_ru || ""}
                  onChange={(value) =>
                    setForm((s) => ({ ...s, content_ru: value }))
                  }
                  className="bg-gray-900 h-48"
                  placeholder={t("Yordam matnini kiriting...") + " (ru)"}
                />
              </div>
              {errors.content && (
                <p className="text-destructive text-sm mt-12">
                  {t(errors.content)}
                </p>
              )}
            </div>

            <div className="grid grid-cols-1 gap-4 mt-5">
              <div>
                <label className="text-sm font-medium">
                  {t("Sahifa turi")}
                </label>
                <Select
                  value={form.page_type}
                  onValueChange={(value) =>
                    setForm((s) => ({
                      ...s,
                      page_type: value as "privacy_policy" | "user_agreement",
                    }))
                  }
                  disabled={editing !== null}
                >
                  <SelectTrigger className="mt-1 w-full !h-12">
                    <SelectValue placeholder={t("Sahifa turini tanlang")} />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="user_agreement" disabled={legalExists}>
                      {t("Qo‘llanma")}
                    </SelectItem>
                    <SelectItem
                      value="privacy_policy"
                      disabled={individualExists}
                    >
                      {t("Maxfiylik siyosati")}
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="flex items-end">
                <label className="flex items-center gap-2 text-sm cursor-pointer">
                  <Checkbox
                    checked={!!form.is_active}
                    onCheckedChange={(checked) =>
                      setForm((s) => ({ ...s, active: checked ? true : false }))
                    }
                  />
                  <span>{t("Faol")}</span>
                </label>
              </div>
            </div>

            <div className="flex gap-2 pt-4">
              <Button
                onClick={handleCreateOrUpdate}
                disabled={isAddDisabled}
                className="bg-blue-600 hover:bg-blue-700"
              >
                {editing ? t("Saqlash") : t("Yaratish")}
              </Button>
              <Button variant="outline" onClick={resetForm}>
                {t("Bekor qilish")}
              </Button>
            </div>
          </CardContent>
        </Card>

        <div className="space-y-3">
          {items?.length === 0 && (
            <Card>
              <CardContent className="pt-6">
                <p className="text-muted-foreground text-center">
                  {t("Natija topilmadi.")}
                </p>
              </CardContent>
            </Card>
          )}

          {items?.map((it) => (
            <Card key={it.id} className="overflow-hidden">
              <CardContent className="pt-6">
                <div className="flex flex-col md:flex-row md:items-start md:justify-between gap-4">
                  <div className="flex-1">
                    <h3 className="font-semibold text-lg">{it.title}</h3>
                    <p className="mt-3 text-sm line-clamp-3">{it.content}</p>
                  </div>

                  <div className="flex gap-2 items-center flex-wrap md:flex-col md:flex-nowrap">
                    <Button
                      onClick={() => startEdit(it.id)}
                      variant="outline"
                      className="w-full"
                      size="sm"
                    >
                      <Edit2 className="w-4 h-4 mr-1" />
                      {t("Tahrirlash")}
                    </Button>

                    <Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>
                      <DialogTrigger asChild>
                        <Button
                          variant="destructive"
                          size="sm"
                          className="w-full"
                          onClick={() => setDeleteOpen(true)}
                        >
                          <Trash2 className="w-4 h-4 mr-1" />
                          {t("O'chirish")}
                        </Button>
                      </DialogTrigger>
                      <DialogContent>
                        <DialogTitle>{t("O‘chirishni tasdiqlash")}</DialogTitle>
                        <DialogDescription>
                          {t(
                            "Haqiqatan ham bu yordam sahifasini o‘chirmoqchimisiz? Bu amalni bekor qilib bo‘lmaydi.",
                          )}
                        </DialogDescription>
                        <div className="flex gap-3 justify-end pt-4">
                          <Button onClick={() => setDeleteOpen(false)}>
                            {t("Bekor qilish")}
                          </Button>
                          <Button
                            variant={"destructive"}
                            onClick={() => removeItem(it.id)}
                          >
                            {t("O'chirish")}
                          </Button>
                        </div>
                      </DialogContent>
                    </Dialog>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    </div>
  );
}
