"use client";

import React, { useEffect, useRef, useState } from "react";
import Image from "next/image";
import Modal from "@/components/elements/Modal";
import RoundedButton from "@/components/elements/RoundedButton";
import RoundedInput from "@/components/elements/RoundedInput";
import SelectBox from "@/components/elements/SelectBox";
import useAxios from "@/hooks/useAxios";
import { ICity, IExpertise, IProvince } from "@/types/types";
import toast from "react-hot-toast";
import BoldIcon from "@/components/ui/BoldIcon";
import ChatRoomMemberPicker, {
  ChatRoomMember,
} from "@/components/chat/ChatRoomMemberPicker";
import { cn } from "@/lib/utils";
import { filterChipClass } from "@/lib/ui/buttonStyles";
import { useTranslation } from "react-i18next";
import { getStoredUserId } from "@/lib/auth/session";
import { ensureIdentityKeys, ensureRoomAesKey } from "@/lib/e2ee";

type Props = {
  open: boolean;
  onClose: () => void;
  onCreated: () => void;
};

type RoomVisibility = "public" | "private";

export default function CreateChatRoomModal({ open, onClose, onCreated }: Props) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const fileRef = useRef<HTMLInputElement>(null);
  const [title, setTitle] = useState("");
  const [visibility, setVisibility] = useState<RoomVisibility>("public");
  const [provinceId, setProvinceId] = useState("");
  const [cityId, setCityId] = useState("");
  const [expertise, setExpertise] = useState("");
  const [invitedMembers, setInvitedMembers] = useState<ChatRoomMember[]>([]);
  const [idleTimeoutDays, setIdleTimeoutDays] = useState(30);
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [provinces, setProvinces] = useState<IProvince[]>([]);
  const [cities, setCities] = useState<ICity[]>([]);
  const [expertiseList, setExpertiseList] = useState<IExpertise[]>([]);
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    if (!open) return;
    setTitle("");
    setVisibility("public");
    setProvinceId("");
    setCityId("");
    setExpertise("");
    setInvitedMembers([]);
    setIdleTimeoutDays(30);
    setImageFile(null);
    setImagePreview(null);

    void request<{ provinces: IProvince[] }>("GET", "/provinces", null, {
      noToast: true,
    }).then((res) => setProvinces(res?.provinces ?? []));

    void request<{ expertises: IExpertise[] }>("GET", "/expertise", null, {
      noToast: true,
    }).then((res) => setExpertiseList(res?.expertises ?? []));
  }, [open, request]);

  useEffect(() => {
    if (!provinceId) {
      setCities([]);
      setCityId("");
      return;
    }
    void request<{ cities: ICity[] }>(
      "GET",
      `/cities/${provinceId}`,
      null,
      { noToast: true }
    ).then((res) => setCities(res?.cities ?? []));
  }, [provinceId, request]);

  const onPickImage = (file: File | null) => {
    setImageFile(file);
    if (!file) {
      setImagePreview(null);
      return;
    }
    const reader = new FileReader();
    reader.onload = () => setImagePreview(String(reader.result));
    reader.readAsDataURL(file);
  };

  const submit = async () => {
    if (!title.trim()) {
      toast.error(t("chats.toast.roomNameRequired"));
      return;
    }
    if (visibility === "private" && invitedMembers.length === 0) {
      toast.error(t("chats.toast.privateRoomMembersRequired"));
      return;
    }

    setSubmitting(true);
    try {
      const form = new FormData();
      form.append("title", title.trim());
      form.append("visibility", visibility);
      if (visibility === "public") {
        if (provinceId) form.append("province_id", provinceId);
        if (cityId) form.append("city_id", cityId);
        if (expertise) form.append("expertise", expertise);
      } else {
        form.append(
          "member_ids",
          JSON.stringify(invitedMembers.map((member) => member._id))
        );
      }
      form.append("idle_timeout_days", String(idleTimeoutDays));
      if (imageFile) form.append("room_image", imageFile);

      const created = await request<{ room?: { _id?: string } }>(
        "POST",
        "/chat-rooms",
        form
      );
      const newRoomId = created?.room?._id;
      const uid = getStoredUserId();
      if (newRoomId && uid) {
        try {
          await ensureIdentityKeys(String(uid));
          await ensureRoomAesKey(String(uid), String(newRoomId));
        } catch {
          /* e2ee bootstrap best-effort */
        }
      }
      toast.success(t("chats.toast.roomCreated"));
      onCreated();
      onClose();
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { error?: string; message?: string } } })
          ?.response?.data?.error ||
        (err as { response?: { data?: { message?: string } } })?.response?.data
          ?.message;
      toast.error(message || t("chats.toast.createRoomFailed"));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Modal
      isOpen={open}
      onClose={onClose}
      height="fit"
      elevated
      panelClassName="!p-0 max-h-[90dvh] w-full overflow-y-auto overscroll-y-contain touch-pan-y [-webkit-overflow-scrolling:touch]"
    >
      <div className="px-4 pt-5 pb-[calc(6rem+env(safe-area-inset-bottom,0px))]">
        <div className="mx-auto flex w-full max-w-sm flex-col items-center">
          <span className="mb-4 block text-center font-semibold">
            {t("chats.modal.createRoomTitle")}
          </span>

          <button
            type="button"
            onClick={() => fileRef.current?.click()}
            className="gentle-transition relative mb-4 h-24 w-24 overflow-hidden rounded-full border border-neutral-200 bg-neutral-100 dark:border-neutral-700 dark:bg-neutral-800"
          >
            {imagePreview ? (
              <Image src={imagePreview} alt="" fill className="object-cover" />
            ) : (
              <span className="flex h-full w-full flex-col items-center justify-center gap-1 text-[11px] text-neutral-500">
                <BoldIcon name="gallery-add" size={22} />
                {t("chats.modal.roomImage")}
              </span>
            )}
          </button>
          <input
            ref={fileRef}
            type="file"
            accept="image/*"
            className="hidden"
            onChange={(e) => onPickImage(e.target.files?.[0] ?? null)}
          />

          <div className="mb-4 w-full">
            <p className="mb-1.5 text-center text-xs text-neutral-500">
              {t("chats.modal.roomName")}
            </p>
            <RoundedInput
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder={t("chats.placeholder.roomName")}
              className="text-center text-sm"
            />
          </div>

          <div className="mb-4 w-full">
            <p className="mb-2 text-center text-xs text-neutral-500">
              {t("chats.modal.idleTimeout")}
            </p>
            <div className="flex flex-wrap justify-center gap-2">
              {[1, 2, 7, 14, 30].map((days) => (
                <button
                  key={days}
                  type="button"
                  onClick={() => setIdleTimeoutDays(days)}
                  className={filterChipClass(idleTimeoutDays === days)}
                >
                  {t("chats.modal.idleTimeoutDays", { count: days })}
                </button>
              ))}
            </div>
            <p className="mt-2 px-2 text-center text-[11px] leading-5 text-neutral-500">
              {t("chats.modal.idleTimeoutHint")}
            </p>
          </div>

          <div className="mb-4 w-full">
            <p className="mb-2 text-center text-xs text-neutral-500">
              {t("chats.modal.roomType")}
            </p>
            <div className="flex gap-2 rounded-full bg-neutral-100 p-1 dark:bg-neutral-800">
              <button
                type="button"
                onClick={() => setVisibility("public")}
                className={cn(
                  "flex-1 rounded-full py-2 text-sm font-medium transition-colors",
                  visibility === "public"
                    ? "bg-white text-[#0095f6] shadow-sm dark:bg-neutral-900"
                    : "text-neutral-500"
                )}
              >
                {t("chats.modal.public")}
              </button>
              <button
                type="button"
                onClick={() => setVisibility("private")}
                className={cn(
                  "flex-1 rounded-full py-2 text-sm font-medium transition-colors",
                  visibility === "private"
                    ? "bg-white text-[#0095f6] shadow-sm dark:bg-neutral-900"
                    : "text-neutral-500"
                )}
              >
                {t("chats.modal.private")}
              </button>
            </div>
          </div>

          {visibility === "private" ? (
            <div className="mb-4 w-full">
              <p className="mb-2 text-center text-xs text-neutral-500">
                {t("chats.modal.inviteUsers")}
              </p>
              <ChatRoomMemberPicker
                selected={invitedMembers}
                onChange={setInvitedMembers}
              />
              <p className="mt-2 px-2 text-center text-[11px] leading-5 text-neutral-500">
                {t("chats.modal.privateRoomHint")}
              </p>
            </div>
          ) : (
            <>
              <div className="mb-4 w-full">
                <p className="mb-1.5 text-center text-xs text-neutral-500">
                  {t("chats.modal.provinceOptional")}
                </p>
                <SelectBox
                  value={provinceId}
                  onChange={(e) => {
                    setProvinceId(e.target.value);
                    setCityId("");
                  }}
                  className="text-sm"
                >
                  <option value="">{t("chats.modal.allProvinces")}</option>
                  {provinces.map((item) => (
                    <option key={item.id} value={item.id}>
                      {item.name}
                    </option>
                  ))}
                </SelectBox>
              </div>

              <div className="mb-4 w-full">
                <p className="mb-1.5 text-center text-xs text-neutral-500">
                  {t("chats.modal.cityOptional")}
                </p>
                <SelectBox
                  value={cityId}
                  onChange={(e) => setCityId(e.target.value)}
                  disabled={!provinceId}
                  className="text-sm"
                >
                  <option value="">{t("chats.modal.allCities")}</option>
                  {cities.map((item) => (
                    <option key={item.id} value={item.id}>
                      {item.name}
                    </option>
                  ))}
                </SelectBox>
              </div>

              <div className="mb-2 w-full">
                <p className="mb-1.5 text-center text-xs text-neutral-500">
                  {t("chats.modal.expertiseOptional")}
                </p>
                <SelectBox
                  value={expertise}
                  onChange={(e) => setExpertise(e.target.value)}
                  className="text-sm"
                >
                  <option value="">{t("chats.modal.allExpertise")}</option>
                  {expertiseList.map((item) => (
                    <option key={item._id} value={item.expertise}>
                      {item.expertise}
                    </option>
                  ))}
                </SelectBox>
              </div>

              <p className="mb-4 px-2 text-center text-[11px] leading-5 text-neutral-500">
                {t("chats.modal.publicRoomHint")}
              </p>
            </>
          )}

          <div className="mt-2 flex w-full flex-col items-center gap-3 border-t border-neutral-200 pt-5 dark:border-neutral-700">
            <RoundedButton
              type="button"
              variant="primary"
              disabled={submitting}
              onClick={() => void submit()}
              className="h-10 w-full max-w-[200px] text-sm"
            >
              {submitting ? t("chats.actions.creatingRoom") : t("chats.actions.createRoom")}
            </RoundedButton>
            <RoundedButton
              type="button"
              onClick={onClose}
              className="h-10 w-full max-w-[200px] text-sm"
            >
              {t("chats.actions.cancel")}
            </RoundedButton>
          </div>
        </div>
      </div>
    </Modal>
  );
}
