"use client";

import {
  createSiteSetting,
  deleteSiteSetting,
  getDetailSiteSetting,
  getSiteSetting,
  updateSiteSetting,
} from "@/pages/tour-settings/lib/api";
import formatPhone from "@/shared/lib/formatPhone";
import { Button } from "@/shared/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/ui/card";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/ui/dialog";
import { Input } from "@/shared/ui/input";
import { Label } from "@/shared/ui/label";
import { Map, Placemark, YMaps } from "@pbe/react-yandex-maps";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Edit, Loader2, Plus, Trash } from "lucide-react";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

type MapClickEvent = {
  get: (key: "coords") => [number, number];
};

type ContactInfo = {
  telegram: string;
  instagram: string;
  telegram_chat: string;
  facebook: string;
  twiter: string;
  linkedin: string;
  address: string;
  email: string;
  phonePrimary: string;
  phoneSecondary: string;
};

async function getAddressFromCoords(lat: number, lon: number) {
  const response = await fetch(
    `https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lon}&format=json&accept-language=uz`,
  );
  const data = await response.json();
  return data.display_name || "";
}

export default function ContactSettings() {
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState<number | null>(null);
  const [form, setForm] = useState<ContactInfo>({
    telegram: "",
    telegram_chat: "",
    instagram: "",
    facebook: "",
    twiter: "",
    linkedin: "",
    address: "",
    email: "",
    phonePrimary: "+998",
    phoneSecondary: "+998",
  });
  const [coords, setCoords] = useState({
    latitude: 41.311081,
    longitude: 69.240562,
  });
  const { mutate: create, isPending } = useMutation({
    mutationFn: (body: {
      address: string;
      latitude: string;
      longitude: string;
      telegram: string;
      instagram: string;
      facebook: string;
      twitter: string;
      email: string;
      telegram_chat: string;
      linkedin: string;
      main_phone: string;
      other_phone: string;
    }) => createSiteSetting(body),
    onSuccess: () => {
      setForm({
        telegram: "",
        telegram_chat: "",
        instagram: "",
        facebook: "",
        twiter: "",
        linkedin: "",
        address: "",
        email: "",
        phonePrimary: "",
        phoneSecondary: "",
      });
      setOpen(false);
      queryClient.refetchQueries({ queryKey: ["contact"] });
      queryClient.refetchQueries({ queryKey: ["contact_detail"] });
      setEditing(null);
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        position: "top-center",
        richColors: true,
      });
    },
  });

  const { mutate: update } = useMutation({
    mutationFn: ({
      body,
      id,
    }: {
      id: number;
      body: {
        address: string;
        latitude: string;
        longitude: string;
        telegram: string;
        instagram: string;
        facebook: string;
        telegram_chat: string;
        linkedin: string;
        twitter: string;
        email: string;
        main_phone: string;
        other_phone: string;
      };
    }) => updateSiteSetting({ body, id }),
    onSuccess: () => {
      setForm({
        telegram: "",
        telegram_chat: "",
        instagram: "",
        facebook: "",
        twiter: "",
        linkedin: "",
        address: "",
        email: "",
        phonePrimary: "",
        phoneSecondary: "",
      });
      setOpen(false);
      queryClient.refetchQueries({ queryKey: ["contact"] });
      queryClient.refetchQueries({ queryKey: ["contact_detail"] });
      setEditing(null);
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        position: "top-center",
        richColors: true,
      });
    },
  });

  const { mutate: remover } = useMutation({
    mutationFn: (id: number) => deleteSiteSetting(id),
    onSuccess: () => {
      setForm({
        telegram: "",
        telegram_chat: "",
        instagram: "",
        facebook: "",
        twiter: "",
        linkedin: "",
        address: "",
        email: "",
        phonePrimary: "",
        phoneSecondary: "",
      });
      setOpen(false);
      queryClient.refetchQueries({ queryKey: ["contact"] });
      queryClient.refetchQueries({ queryKey: ["contact_detail"] });
      setEditing(null);
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        position: "top-center",
        richColors: true,
      });
    },
  });

  const { data, isLoading } = useQuery({
    queryKey: ["contact"],
    queryFn: () => {
      return getSiteSetting();
    },
    select: (data) => {
      return data.data.data;
    },
  });

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

  useEffect(() => {
    if (editing && detail) {
      setForm({
        address: detail.address,
        email: detail.email,
        facebook: detail.facebook,
        instagram: detail.instagram,
        linkedin: detail.linkedin,
        phonePrimary: detail.main_phone,
        phoneSecondary: detail.other_phone,
        telegram: detail.telegram,
        telegram_chat: detail.telegram_chat,
        twiter: detail.twitter,
      });
      setCoords({
        latitude: Number(detail.latitude),
        longitude: Number(detail.longitude),
      });
    }
  }, [editing, detail]);

  const handleChange = <K extends keyof ContactInfo>(
    key: K,
    value: ContactInfo[K],
  ) => {
    setForm((s) => ({ ...s, [key]: value }));
  };

  const handleMapClick = async (e: MapClickEvent) => {
    const lat = e.get("coords")[0];
    const lon = e.get("coords")[1];
    setCoords({ latitude: lat, longitude: lon });

    const addressName = await getAddressFromCoords(lat, lon);
    setForm((s) => ({ ...s, address: addressName }));
  };

  const saveContact = () => {
    const shortLat = Number(coords.latitude.toFixed(6));
    const shortLon = Number(coords.longitude.toFixed(6));

    // Majburiy maydonlar tekshiruvi
    if (!form.address.trim()) {
      toast.error(t("Manzilni kiriting!"), {
        position: "top-center",
        richColors: true,
      });
      return;
    }

    if (!form.phonePrimary.trim() || form.phonePrimary.length < 9) {
      toast.error(t("Asosiy telefon raqamini to‘g‘ri kiriting!"), {
        position: "top-center",
        richColors: true,
      });
      return;
    }

    if (!coords.latitude || !coords.longitude) {
      toast.error(t("Xaritadan joy tanlang! (latitude/longitude majburiy)"), {
        position: "top-center",
        richColors: true,
      });
      return;
    }
    if (editing) {
      update({
        body: {
          address: form.address,
          email: form.email,
          facebook: form.facebook,
          linkedin: form.linkedin,
          telegram_chat: form.telegram_chat,
          instagram: form.instagram,
          latitude: String(shortLat),
          longitude: String(shortLon),
          main_phone: form.phonePrimary,
          other_phone: form.phoneSecondary,
          telegram: form.telegram,
          twitter: form.twiter,
        },
        id: editing,
      });
    } else {
      create({
        address: form.address,
        email: form.email,
        linkedin: form.linkedin,
        telegram_chat: form.telegram_chat,
        facebook: form.facebook,
        instagram: form.instagram,
        latitude: String(shortLat),
        longitude: String(shortLon),
        main_phone: form.phonePrimary,
        other_phone: form.phoneSecondary,
        telegram: form.telegram,
        twitter: form.twiter,
      });
    }
  };

  const startAdd = () => {
    setForm({
      telegram: "",
      instagram: "",
      facebook: "",
      twiter: "",
      telegram_chat: "",
      linkedin: "",
      address: "",
      email: "",
      phonePrimary: "",
      phoneSecondary: "",
    });
    setEditing(null);
    setOpen(true);
  };

  const startEdit = (id: number) => {
    setEditing(id);
    setOpen(true);
  };

  const removeContact = (id: number) => {
    remover(id);
  };

  return (
    <div className="w-full h-screen mx-auto p-4">
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-2xl font-semibold text-gray-100">
          {t("Contact settings")}
        </h2>
        {data && data?.total_items === 0 && (
          <Button onClick={startAdd} className="flex items-center gap-2">
            <Plus size={16} /> {t("Qo'shish")}
          </Button>
        )}
      </div>
      {isLoading ? (
        <div className="flex justify-center items-center h-60">
          <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
          <span className="ml-2 text-gray-400">{t("Yuklanmoqda...")}</span>
        </div>
      ) : (
        <>
          {data && data?.total_items === 0 ? (
            <Card className="bg-gray-900">
              <CardHeader>
                <CardTitle>
                  {t("Hozircha kontakt ma'lumotlari qo'shilmagan")}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground">
                  {t(
                    "Sayt uchun telegram, instagram, manzil, email va telefonni bu yerda saqlang. Siz faqat bir marta qo'sha olasiz — keyin tahrirlash mumkin.",
                  )}
                </p>
                <div className="mt-4">
                  <Button
                    onClick={startAdd}
                    className="flex items-center gap-2"
                  >
                    <Plus size={14} /> {t("Qo'shish")}
                  </Button>
                </div>
              </CardContent>
            </Card>
          ) : (
            <>
              {data &&
                data.results.map((e) => (
                  <Card className="bg-gray-900">
                    <CardHeader className="flex items-center justify-between">
                      <CardTitle>{t("Kontakt ma'lumotlari")}</CardTitle>
                      <div className="flex gap-2">
                        <Button
                          variant="outline"
                          onClick={() => startEdit(e.id)}
                          className="flex items-center gap-2"
                        >
                          <Edit size={14} /> {t("Tahrirlash")}
                        </Button>
                        <Button
                          variant="destructive"
                          onClick={() => removeContact(e.id)}
                          className="flex items-center gap-2"
                        >
                          <Trash size={14} /> {t("O'chirish")}
                        </Button>
                      </div>
                    </CardHeader>
                    <CardContent>
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                          <div className="text-sm text-muted-foreground">
                            Telegram
                          </div>
                          <div className="text-sm">{e.telegram || "—"}</div>
                        </div>
                        <div>
                          <div className="text-sm text-muted-foreground">
                            Telegram Chat
                          </div>
                          <div className="text-sm">
                            {e.telegram_chat || "—"}
                          </div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground">
                            Instagram
                          </div>
                          <div className="text-sm">{e.instagram || "—"}</div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground">
                            Instagram
                          </div>
                          <div className="text-sm">{e.linkedin || "—"}</div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground">
                            Facebook
                          </div>
                          <div className="text-sm">{e.facebook || "—"}</div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground">
                            Twitter
                          </div>
                          <div className="text-sm">{e.twitter || "—"}</div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground">
                            {t("Manzil")}
                          </div>
                          <div className="text-sm">{e.address || "—"}</div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground">
                            Email
                          </div>
                          <div className="text-sm">{e.email || "—"}</div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground">
                            {t("Telefon raqam")}
                          </div>
                          <p>{e.main_phone}</p>
                          <p>{e.other_phone}</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
            </>
          )}
        </>
      )}
      {/* Dialog */}
      <Dialog
        open={open}
        onOpenChange={(v) => {
          setOpen(v);
          if (!v) setEditing(null);
        }}
      >
        <DialogContent className="h-[90%] overflow-y-scroll">
          <DialogHeader>
            <DialogTitle>
              {editing ? t("Kontaktni tahrirlash") : t("Kontakt qo'shish")}
            </DialogTitle>
          </DialogHeader>

          {/* Map */}
          <YMaps query={{ lang: "en_RU" }}>
            <Map
              defaultState={{
                center: [coords.latitude, coords.longitude],
                zoom: 13,
              }}
              width="100%"
              la
              height="400px"
              onClick={handleMapClick}
            >
              <Placemark geometry={[coords.latitude, coords.longitude]} />
            </Map>
          </YMaps>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 mt-4">
            <div className="flex flex-col gap-2 sm:col-span-2">
              <Label>{t("Manzil")}</Label>
              <Input
                value={form.address || ""}
                onChange={(e) => handleChange("address", e.target.value)}
              />
            </div>
            <div className="flex flex-col gap-2">
              <Label>Telegram</Label>
              <Input
                value={form.telegram || ""}
                onChange={(e) => handleChange("telegram", e.target.value)}
              />
            </div>
            <div className="flex flex-col gap-2">
              <Label>Telegram Chat</Label>
              <Input
                value={form.telegram_chat || ""}
                onChange={(e) => handleChange("telegram_chat", e.target.value)}
              />
            </div>
            <div className="flex flex-col gap-2">
              <Label>Instagram</Label>
              <Input
                value={form.instagram || ""}
                onChange={(e) => handleChange("instagram", e.target.value)}
              />
            </div>
            <div className="flex flex-col gap-2">
              <Label>Linkedin</Label>
              <Input
                value={form.linkedin || ""}
                onChange={(e) => handleChange("linkedin", e.target.value)}
              />
            </div>
            <div className="flex flex-col gap-2">
              <Label>Facebook</Label>
              <Input
                value={form.facebook || ""}
                onChange={(e) => handleChange("facebook", e.target.value)}
              />
            </div>
            <div className="flex flex-col gap-2">
              <Label>Twitter</Label>
              <Input
                value={form.twiter || ""}
                onChange={(e) => handleChange("twiter", e.target.value)}
              />
            </div>
            <div className="flex flex-col gap-2">
              <Label>Email</Label>
              <Input
                value={form.email || ""}
                onChange={(e) => handleChange("email", e.target.value)}
              />
            </div>
            <div className="flex flex-col gap-2">
              <Label>{t("Asosiy telefon")}</Label>
              <Input
                value={formatPhone(form.phonePrimary)}
                onChange={(e) => handleChange("phonePrimary", e.target.value)}
              />
            </div>
            <div className="flex flex-col gap-2 w-full">
              <Label>{t("Qo'shimcha telefon")}</Label>
              <Input
                value={formatPhone(form.phoneSecondary)}
                onChange={(e) => handleChange("phoneSecondary", e.target.value)}
              />
            </div>
          </div>

          <DialogFooter className="mt-6 flex justify-end gap-2">
            <Button
              variant="ghost"
              onClick={() => {
                setOpen(false);
                setEditing(null);
              }}
            >
              {t("Bekor qilish")}
            </Button>
            <Button onClick={saveContact}>
              {isPending ? <Loader2 className="animate-spin" /> : t("Saqlash")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
