
import { useEffect, useState } from "react";
import { toast } from "react-toastify";
import {
  getJurorSocialLinks,
  addUpdateSocialLinks,
} from "@/services/jurorsService";
import { useParams } from "next/navigation";
import Layout from "@/Layout";
import Link from "next/link";

export default function SocialLinksModal({ isComprehensive }) {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const params = useParams();
  const jurorId = params.id;

  const [form, setForm] = useState({
    facebook: "",
    linkedin: "",
    twitter: "",
    truth_social: "",
    general: "",
  });
  const baseRoute = isComprehensive
    ? "/comprehensive-report"
    : "/juror-management";

  useEffect(() => {
    loadData();
  }, [jurorId]);

  const loadData = async () => {
    try {
      setLoading(true);

      const res = await getJurorSocialLinks(jurorId);

      const data = Array.isArray(res.data) ? res.data[0] : res.data;

      if (data) {
        setForm({
          facebook: data.facebook || "",
          linkedin: data.linkedin || "",
          twitter: data.twitter || "",
          truth_social: data.truth_social || "",
          general: data.general || "",
        });
      }
    } catch (err) {
      toast.error("Failed to load social links");
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (e) => {
    setForm({
      ...form,
      [e.target.name]: e.target.value,
    });
  };

  const saveChanges = async () => {
    try {
      setSaving(true);

      await addUpdateSocialLinks(jurorId, form);

      toast.success("Social links updated");

    } catch (err) {
      toast.error("Failed to update");
    } finally {
      setSaving(false);
    }
  };

  const handleRedirect = (url) => {
    if (!url) return;

    let formattedUrl = url.trim();

    if (!/^https?:\/\//i.test(formattedUrl)) {
      formattedUrl = `https://${formattedUrl}`;
    }

    window.open(formattedUrl, "_blank", "noopener,noreferrer");
  };

  return (
    <Layout title="Social Links">
      {/* Breadcrumb */}
      <div className="pagerlink mb-3">
        <ul>
          <li>
            <Link href="/dashboard">Dashboard</Link>
          </li>
          <li>
            <Link href={baseRoute}>
              {isComprehensive ? "Comprehensive Report" : "Juror Management"}
            </Link>
          </li>
          <li>Social Links</li>
        </ul>
      </div>
      <div className="dshboardwhtepnel">
        <div className="dshboardcaseform">
          <h3>Social Links</h3>
          <p className="mb-4">
            Update juror social media links.
          </p>

          {loading ? (
            <div className="text-center py-5">
              <p>Loading...</p>
            </div>
          ) : (
            <>
              <div className="row">

                {/* Facebook */}
                <div className="col-md-6 mb-3">
                  <label className="d-block text-start">Facebook</label>

                  <div className="d-flex align-items-center gap-2">
                    <input
                      className="form-control"
                      name="facebook"
                      value={form.facebook}
                      onChange={handleChange}
                    />

                    <button
                      type="button"
                      className="btn btn-outline-secondary"
                      disabled={!form.facebook}
                      onClick={() => handleRedirect(form.facebook)}
                      title="Open Facebook"
                    >
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width="15"
                        height="15"
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                        strokeWidth={2}
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
                        />
                      </svg>
                    </button>
                  </div>
                </div>

                {/* LinkedIn */}
                <div className="col-md-6 mb-3">
                  <label className="d-block text-start">LinkedIn</label>

                  <div className="d-flex align-items-center gap-2">
                    <input
                      className="form-control"
                      name="linkedin"
                      value={form.linkedin}
                      onChange={handleChange}
                    />

                    <button
                      type="button"
                      className="btn btn-outline-secondary"
                      disabled={!form.linkedin}
                      onClick={() => handleRedirect(form.linkedin)}
                      title="Open LinkedIn"
                    >
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width="15"
                        height="15"
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                        strokeWidth={2}
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
                        />
                      </svg>
                    </button>
                  </div>
                </div>

                {/* Twitter / X */}
                <div className="col-md-6 mb-3">
                  <label className="d-block text-start">Twitter / X</label>

                  <div className="d-flex align-items-center gap-2">
                    <input
                      className="form-control"
                      name="twitter"
                      value={form.twitter}
                      onChange={handleChange}
                    />

                    <button
                      type="button"
                      className="btn btn-outline-secondary"
                      disabled={!form.twitter}
                      onClick={() => handleRedirect(form.twitter)}
                      title="Open Twitter"
                    >
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width="15"
                        height="15"
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                        strokeWidth={2}
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
                        />
                      </svg>
                    </button>
                  </div>
                </div>

                {/* Truth Social */}
                <div className="col-md-6 mb-3">
                  <label className="d-block text-start">Truth Social</label>

                  <div className="d-flex align-items-center gap-2">
                    <input
                      className="form-control"
                      name="truth_social"
                      value={form.truth_social}
                      onChange={handleChange}
                    />

                    <button
                      type="button"
                      className="btn btn-outline-secondary"
                      disabled={!form.truth_social}
                      onClick={() => handleRedirect(form.truth_social)}
                      title="Open Truth Social"
                    >
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width="15"
                        height="15"
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                        strokeWidth={2}
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
                        />
                      </svg>
                    </button>
                  </div>
                </div>

                {/* General */}
                <div className="col-md-6 mb-3">
                  <label className="d-block text-start">General</label>

                  <div className="d-flex align-items-center gap-2">
                    <input
                      className="form-control"
                      name="general"
                      value={form.general}
                      onChange={handleChange}
                    />

                    <button
                      type="button"
                      className="btn btn-outline-secondary"
                      disabled={!form.general}
                      onClick={() => handleRedirect(form.general)}
                      title="Open Link"
                    >
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width="15"
                        height="15"
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                        strokeWidth={2}
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
                        />
                      </svg>
                    </button>
                  </div>
                </div>

              </div>

              <div className="datafrmbtn mt-4">
                <ul>
                  <li>
                    <button
                      type="button"
                      className="canselbtn"
                      onClick={() => window.history.back()}
                    >
                      Cancel
                    </button>
                  </li>

                  <li>
                    <button
                      type="button"
                      onClick={saveChanges}
                      disabled={saving}
                    >
                      {saving ? "Saving..." : "Save Changes"}
                    </button>
                  </li>
                </ul>
              </div>
            </>
          )}
        </div>
      </div>
    </Layout>
  );
}