"use client";

import React, { useContext } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { getCookie, setCookie, setLargeStorage } from "@/context/utils/cookies";
import { useSetting } from "@/context/helpers/theme-setting/SettingProvider";
import HomeContext from "@/context/helpers/Home";
import { useTranslation } from "react-i18next";

const BranchSelectionPopup = () => {
  const { t } = useTranslation("home");
  const { selectedStoreBranch, setSelectedStoreBranch } = useSetting();
  const homeContext = useContext(HomeContext);
  const locale =
    typeof window !== "undefined"
      ? getCookie("locale") || localStorage.getItem("locale") || "en"
      : "en";

  if (!homeContext) return null;

  const {
    showBranchesPopup,
    availableBranches,
    selectBranch,
    closeBranchPopup,
  } = homeContext;

  const getBranchName = (branch) => {
    if (branch.translations) {
      const translation = branch.translations.find(
        (trans) => trans.locale === locale
      );
      return translation ? translation.name : branch.name || branch.branch_name;
    }
    return branch.name || branch.branch_name;
  };

  const handleBranchSelect = (branchId) => {
    const branch = availableBranches?.find(
      (b) =>
        String(b.id) === String(branchId) ||
        String(b.branch_id) === String(branchId)
    );

    if (
      selectedStoreBranch &&
      branch &&
      String(branch.id) === String(selectedStoreBranch.id)
    ) {
      closeBranchPopup?.();
      return;
    }

    if (branch) {
      setSelectedStoreBranch?.(branch);
      setLargeStorage("selectedBranch", JSON.stringify(branch));
      setCookie("branchId", String(branch.id || branch.branch_id));
    } else {
      setCookie("branchId", String(branchId));
    }

    // Call context selectBranch to handle popup closure and page reload
    selectBranch?.(branchId);
  };

  return (
    <Dialog open={showBranchesPopup} onOpenChange={closeBranchPopup}>
      <DialogContent className="p-0 rounded-2xl max-w-lg overflow-hidden">
        <DialogHeader className="bg-primary dark:bg-black/10 px-6 py-4 text-white dark:text-white">
          <DialogTitle className="flex items-center gap-2 font-semibold text-lg">
            📍 {t("select_branch")}
          </DialogTitle>
        </DialogHeader>

        <div className="dark:bg-black p-6">
          {/* Intro */}
          <div className="mb-6 text-center">
            <h5 className="mb-1 font-medium text-gray-800 dark:text-white text-base">
              {t("choose_your_location")}
            </h5>
            <p className="text-muted-foreground text-sm">
              {t("branch_selection_message")}
            </p>
          </div>

          {/* Branches List */}
          <div className="space-y-3">
            {availableBranches && availableBranches.length > 0 ? (
              availableBranches.map((branch) => (
                <div
                  key={branch.id || branch.branch_id}
                  onClick={() =>
                    handleBranchSelect(branch.id || branch.branch_id)
                  }
                  className="flex items-start gap-3 hover:shadow-md p-4 border hover:border-primary rounded-lg transition active:translate-y-[1px] cursor-pointer"
                >
                  <div className="text-2xl">🏪</div>
                  <div className="flex-1">
                    <h6 className="font-semibold text-sm">
                      {getBranchName(branch)}
                    </h6>
                    {branch.address && (
                      <p className="flex items-center gap-1 text-muted-foreground text-xs">
                        📍 {branch.address}
                      </p>
                    )}
                    {branch.phone && (
                      <p className="flex items-center gap-1 text-muted-foreground text-xs">
                        📞 {branch.phone}
                      </p>
                    )}
                    {branch.working_hours && (
                      <p className="flex items-center gap-1 text-muted-foreground text-xs">
                        🕒 {branch.working_hours}
                      </p>
                    )}
                  </div>
                  <div className="text-muted-foreground">→</div>
                </div>
              ))
            ) : (
              <div className="py-6 text-center">
                <div className="mb-2 text-3xl">⚠️</div>
                <p className="text-muted-foreground text-sm">
                  {t("no_branches_available")}
                </p>
              </div>
            )}
          </div>

          {/* Footer Help */}
          <div className="mt-6 text-center">
            <p className="flex justify-center items-center gap-1 text-muted-foreground text-xs">
              ℹ️ {t("branch_selection_help")}
            </p>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default BranchSelectionPopup;
