"use client";

import { useEffect, useMemo, useState } from "react";

import { useRouter } from "next/navigation";

import {
  generateKundaliMatch,
  getAshtakootBreakdown,
  getSavedMatches,
  saveMatch,
  deleteSavedMatch,
  SavedMatch,
} from "@/app/lib/kundaliMatch";
import { PlaceDetails } from "@/app/lib/places";
import Header from "@/app/components/layout/Header";
import Footer from "@/app/components/layout/Footer";
import PlaceAutocomplete from "@/app/components/PlaceAutocomplete";
import { useLanguage } from "@/app/context/LanguageContext";
import { toContentLang } from "@/app/i18n/locales";
import "./kundli-matching.css";

export default function KundaliMatchingPage() {
  const router = useRouter();

  const { locale } = useLanguage();

  const contentLocale = toContentLang(locale);

  /*
  |--------------------------------------------------------------------------
  | Boy
  |--------------------------------------------------------------------------
  */

  const [boyName, setBoyName] = useState("");

  const [boyBirthDate, setBoyBirthDate] = useState("");

  const [boyBirthTime, setBoyBirthTime] = useState("");

  const [boyBirthPlace, setBoyBirthPlace] = useState("");

  const [boyLatitude, setBoyLatitude] = useState(26.9124);

  const [boyLongitude, setBoyLongitude] = useState(75.7873);

  const [boyTimezone, setBoyTimezone] = useState(5.5);

  /*
  |--------------------------------------------------------------------------
  | Girl
  |--------------------------------------------------------------------------
  */

  const [girlName, setGirlName] = useState("");

  const [girlBirthDate, setGirlBirthDate] = useState("");

  const [girlBirthTime, setGirlBirthTime] = useState("");

  const [girlBirthPlace, setGirlBirthPlace] = useState("");

  const [girlLatitude, setGirlLatitude] = useState(28.6139);

  const [girlLongitude, setGirlLongitude] = useState(77.209);

  const [girlTimezone, setGirlTimezone] = useState(5.5);

  /*
  |--------------------------------------------------------------------------
  | Match Type
  |--------------------------------------------------------------------------
  */

  const [matchType, setMatchType] = useState<"north" | "south">("north");

  /*
  |--------------------------------------------------------------------------
  | Location
  |--------------------------------------------------------------------------
  */

  const handleBoyBirthPlaceChange = (value: string) => {
    setBoyBirthPlace(value);
  };

  const handleBoyBirthPlaceSelect = (details: PlaceDetails) => {
    setBoyLatitude(details.latitude);
    setBoyLongitude(details.longitude);
    setBoyTimezone(details.timezone);
  };

  const handleGirlBirthPlaceChange = (value: string) => {
    setGirlBirthPlace(value);
  };

  const handleGirlBirthPlaceSelect = (details: PlaceDetails) => {
    setGirlLatitude(details.latitude);
    setGirlLongitude(details.longitude);
    setGirlTimezone(details.timezone);
  };

  /*
  |--------------------------------------------------------------------------
  | Saved Matches
  |--------------------------------------------------------------------------
  */

  const [savedMatches, setSavedMatches] = useState<SavedMatch[]>([]);

  const [search, setSearch] = useState("");

  /*
  |--------------------------------------------------------------------------
  | Loading
  |--------------------------------------------------------------------------
  */

  const [loading, setLoading] = useState(false);

  const [pageLoading, setPageLoading] = useState(true);

  const [error, setError] = useState("");

  /*
  |--------------------------------------------------------------------------
  | Load user + saved matches
  |--------------------------------------------------------------------------
  */

  useEffect(() => {
    const token = localStorage.getItem("token");

    if (!token) {
      router.replace("/signin");

      return;
    }

    const list = getSavedMatches();

    setSavedMatches(list);

    setPageLoading(false);
  }, [router]);

  /*
  |--------------------------------------------------------------------------
  | Search
  |--------------------------------------------------------------------------
  */

  const filteredMatches = useMemo(() => {
    const keyword = search.trim().toLowerCase();

    if (!keyword) {
      return savedMatches;
    }

    return savedMatches.filter(
      (item) =>
        item.boy.name.toLowerCase().includes(keyword) ||
        item.girl.name.toLowerCase().includes(keyword),
    );
  }, [savedMatches, search]);

  /*
  |--------------------------------------------------------------------------
  | Match Kundli
  |--------------------------------------------------------------------------
  */

  const handleMatch = async () => {
    try {
      setError("");

      /*
        |--------------------------------------------------------------------------
        | Validation
        |--------------------------------------------------------------------------
        */

      if (!boyName.trim() || !girlName.trim()) {
        setError("Please enter both names.");
        return;
      }

      if (!boyBirthDate || !girlBirthDate) {
        setError("Please select both birth dates.");
        return;
      }

      if (!boyBirthTime || !girlBirthTime) {
        setError("Please select both birth times.");
        return;
      }

      if (!boyBirthPlace.trim() || !girlBirthPlace.trim()) {
        setError("Please enter both birth places.");
        return;
      }

      const token = localStorage.getItem("token");

      if (!token) {
        router.replace("/signin");

        return;
      }

      setLoading(true);

      /*
        |--------------------------------------------------------------------------
        | API Payload
        |--------------------------------------------------------------------------
        */

      const payload = {
        boy: {
          name: boyName.trim(),
          gender: "male",
          birth_date: boyBirthDate,
          birth_time: boyBirthTime,
          birth_place: boyBirthPlace.trim(),
          latitude: boyLatitude,
          longitude: boyLongitude,
          timezone: boyTimezone,
        },

        girl: {
          name: girlName.trim(),
          gender: "female",
          birth_date: girlBirthDate,
          birth_time: girlBirthTime,
          birth_place: girlBirthPlace.trim(),
          latitude: girlLatitude,
          longitude: girlLongitude,
          timezone: girlTimezone,
        },

        match_type: matchType,

        lang: contentLocale,
      };

      console.log("Kundali Match Payload:", payload);

      /*
        |--------------------------------------------------------------------------
        | API
        |--------------------------------------------------------------------------
        */

      const response = await generateKundaliMatch(payload);

      console.log("Kundali Match Response:", response);

      /*
        |--------------------------------------------------------------------------
        | Ashtakoot (per-guna) Breakdown
        |--------------------------------------------------------------------------
        |
        | Best-effort — the report still renders (score + doshas
        | only) if this call fails for any reason.
        |
        */

      let ashtakoot: any = null;

      try {
        ashtakoot = await getAshtakootBreakdown(payload);

        console.log("Kundali Ashtakoot Response:", ashtakoot);
      } catch (ashtakootError) {
        console.error("Kundali Ashtakoot Error:", ashtakootError);
      }

      /*
        |--------------------------------------------------------------------------
        | Get API Match ID
        |--------------------------------------------------------------------------
        */

      const apiRecord =
        response?.recordList?.[0] ||
        response?.data?.[0] ||
        response?.data ||
        response;

      const apiId = apiRecord?.id;

      /*
        |--------------------------------------------------------------------------
        | Local ID
        |--------------------------------------------------------------------------
        */

      const localId = apiId ? String(apiId) : `${Date.now()}`;

      /*
        |--------------------------------------------------------------------------
        | Save Match
        |--------------------------------------------------------------------------
        */

      const saved: SavedMatch = {
        localId,

        apiId,

        boy: {
          name: boyName.trim(),
          gender: "Male",
          birthDate: boyBirthDate,
          birthTime: boyBirthTime,
          birthPlace: boyBirthPlace.trim(),
        },

        girl: {
          name: girlName.trim(),
          gender: "Female",
          birthDate: girlBirthDate,
          birthTime: girlBirthTime,
          birthPlace: girlBirthPlace.trim(),
        },

        match_type: matchType,

        response,

        ashtakoot,

        createdAt: new Date().toISOString(),
      };

      saveMatch(saved);

      /*
        |--------------------------------------------------------------------------
        | Update Saved Matches UI
        |--------------------------------------------------------------------------
        */

      setSavedMatches(getSavedMatches());

      /*
        |--------------------------------------------------------------------------
        | Store currently selected match
        |--------------------------------------------------------------------------
        */

      sessionStorage.setItem("current_kundali_match", JSON.stringify(saved));

      /*
        |--------------------------------------------------------------------------
        | Open result page
        |--------------------------------------------------------------------------
        */

      router.push(`/kundli-matching/${encodeURIComponent(localId)}`);
    } catch (error: any) {
      console.error("Kundali Match Error:", error);

      if (error?.message === "AUTH_REQUIRED") {
        router.replace("/signin");

        return;
      }

      setError(
        error?.message || "Unable to match Kundli. Please try again.",
      );
    } finally {
      setLoading(false);
    }
  };

  /*
  |--------------------------------------------------------------------------
  | Delete
  |--------------------------------------------------------------------------
  */

  const handleDelete = (event: React.MouseEvent, localId: string) => {
    event.stopPropagation();

    deleteSavedMatch(localId);

    setSavedMatches(getSavedMatches());
  };

  /*
  |--------------------------------------------------------------------------
  | Open saved match
  |--------------------------------------------------------------------------
  */

  const openMatch = (item: SavedMatch) => {
    sessionStorage.setItem("current_kundali_match", JSON.stringify(item));

    router.push(`/kundli-matching/${encodeURIComponent(item.localId)}`);
  };

  /*
  |--------------------------------------------------------------------------
  | Loading
  |--------------------------------------------------------------------------
  */

  if (pageLoading) {
    return (
      <>
        <Header />
        <main className="horoscope-loading">Loading Kundli Matching...</main>
        <Footer />
      </>
    );
  }

  /*
  |--------------------------------------------------------------------------
  | UI
  |--------------------------------------------------------------------------
  */

  return (
    <>
      <Header />
      <main className="kundli-match-page">
        <div className="kundli-match-container">
          {/* =========================================================
            PAGE HEADER
        ========================================================= */}

          <div className="kundli-match-heading">
            <h1>Free Kundli Matching Online</h1>

            <p>Check horoscope compatibility for marriage by date of birth</p>
          </div>

          {/* =========================================================
            INTRO
        ========================================================= */}

          <section className="kundli-match-intro-card">
            <p>
              AstroEye's free kundli matching (Ashtakoot Milan) tool checks
              horoscope compatibility between bride and groom based on Vedic
              Astrology. It evaluates varna, vashya, tara, yoni, graha maitri,
              gana, bhakoot and nadi koota out of a total of 36 gunas, along
              with mangal dosha and other doshas, to help you make an
              informed decision about marriage compatibility.
            </p>
          </section>

          {/* =========================================================
            TWO COLUMNS
        ========================================================= */}

          <div className="kundli-match-grid">
            {/* =======================================================
              NEW MATCH
          ======================================================= */}

            <section className="new-match-card">
              <h2>New Kundli Match</h2>

              {/* BOY DETAILS */}

              <div className="match-person-section boy">
                <h3>👦 Boy's Details</h3>

                <div className="kundli-field">
                  <label>
                    NAME <span>*</span>
                  </label>

                  <input
                    type="text"
                    value={boyName}
                    onChange={(e) => setBoyName(e.target.value)}
                    placeholder="Enter boy's full name"
                  />
                </div>

                <div className="kundli-row">
                  <div className="kundli-field">
                    <label>
                      BIRTH DATE <span>*</span>
                    </label>

                    <input
                      type="date"
                      value={boyBirthDate}
                      onChange={(e) => setBoyBirthDate(e.target.value)}
                    />
                  </div>

                  <div className="kundli-field">
                    <label>
                      BIRTH TIME <span>*</span>
                    </label>

                    <input
                      type="time"
                      value={boyBirthTime}
                      onChange={(e) => setBoyBirthTime(e.target.value)}
                    />
                  </div>
                </div>

                <div className="kundli-field">
                  <PlaceAutocomplete
                    label="Birth Place *"
                    placeholder="Search city, e.g. Jaipur, India"
                    value={boyBirthPlace}
                    onChange={handleBoyBirthPlaceChange}
                    onSelect={handleBoyBirthPlaceSelect}
                  />
                </div>
              </div>

              {/* GIRL DETAILS */}

              <div className="match-person-section girl">
                <h3>👧 Girl's Details</h3>

                <div className="kundli-field">
                  <label>
                    NAME <span>*</span>
                  </label>

                  <input
                    type="text"
                    value={girlName}
                    onChange={(e) => setGirlName(e.target.value)}
                    placeholder="Enter girl's full name"
                  />
                </div>

                <div className="kundli-row">
                  <div className="kundli-field">
                    <label>
                      BIRTH DATE <span>*</span>
                    </label>

                    <input
                      type="date"
                      value={girlBirthDate}
                      onChange={(e) => setGirlBirthDate(e.target.value)}
                    />
                  </div>

                  <div className="kundli-field">
                    <label>
                      BIRTH TIME <span>*</span>
                    </label>

                    <input
                      type="time"
                      value={girlBirthTime}
                      onChange={(e) => setGirlBirthTime(e.target.value)}
                    />
                  </div>
                </div>

                <div className="kundli-field">
                  <PlaceAutocomplete
                    label="Birth Place *"
                    placeholder="Search city, e.g. Delhi, India"
                    value={girlBirthPlace}
                    onChange={handleGirlBirthPlaceChange}
                    onSelect={handleGirlBirthPlaceSelect}
                  />
                </div>
              </div>

              {/* MATCH TYPE */}

              <div className="match-type-row">
                <label>CHART STYLE</label>

                <div className="match-type-buttons">
                  <button
                    type="button"
                    className={matchType === "north" ? "active" : ""}
                    onClick={() => setMatchType("north")}
                  >
                    North Indian
                  </button>

                  <button
                    type="button"
                    className={matchType === "south" ? "active" : ""}
                    onClick={() => setMatchType("south")}
                  >
                    South Indian
                  </button>
                </div>
              </div>

              {/* ERROR */}

              {error && <div className="kundli-error">{error}</div>}

              {/* MATCH */}

              <button
                type="button"
                className="match-kundli-btn"
                onClick={handleMatch}
                disabled={loading}
              >
                {loading ? "Matching..." : "Match Kundli"}
              </button>
            </section>

            {/* =======================================================
              SAVED MATCHES
          ======================================================= */}

            <section className="saved-match-card">
              <h2>Saved Matches</h2>

              {/* SEARCH */}

              <div className="kundli-search">
                <span>⌕</span>

                <input
                  type="text"
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  placeholder="Search match by name"
                />
              </div>

              <h3>Recently Matched</h3>

              {/* EMPTY */}

              {filteredMatches.length === 0 && (
                <div className="no-match">
                  <p>No saved matches found</p>
                </div>
              )}

              {/* SAVED LIST */}

              {filteredMatches.length > 0 && (
                <div className="saved-match-list">
                  {filteredMatches.map((item) => (
                    <div
                      key={item.localId}
                      className="saved-match-item"
                      onClick={() => openMatch(item)}
                    >
                      <div className="match-avatars">
                        <div className="kundli-avatar boy">
                          {item.boy.name.charAt(0).toUpperCase()}
                        </div>

                        <div className="kundli-avatar girl">
                          {item.girl.name.charAt(0).toUpperCase()}
                        </div>
                      </div>

                      <div className="saved-match-info">
                        <strong>
                          {item.boy.name} & {item.girl.name}
                        </strong>

                        <span>
                          {formatBirthDate(item.boy.birthDate)} •{" "}
                          {item.match_type === "south" ? "South" : "North"}{" "}
                          Chart
                        </span>
                      </div>

                      <button
                        type="button"
                        className="delete-kundli-btn"
                        onClick={(event) => handleDelete(event, item.localId)}
                      >
                        <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 1024 1024">
                          <path d="M0 0h1024v1024H0z" fill="none" />
                          <path fill="currentColor" d="M360 184h-8c4.4 0 8-3.6 8-8zh304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32M731.3 840H292.7l-24.2-512h487z" />
                        </svg>
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </section>
          </div>
        </div>
      </main>
      <Footer />
    </>
  );
}

/*
|--------------------------------------------------------------------------
| Date formatter
|--------------------------------------------------------------------------
*/

function formatBirthDate(date: string) {
  if (!date) {
    return "";
  }

  const parts = date.split("-");

  if (parts.length !== 3) {
    return date;
  }

  return `${parts[2]} ${getMonthName(Number(parts[1]))} ${parts[0]}`;
}

/*
|--------------------------------------------------------------------------
| Month
|--------------------------------------------------------------------------
*/

function getMonthName(month: number) {
  const months = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec",
  ];

  return months[month - 1] || "";
}
