import React, { useState, useRef } from "react";
import SignatureCanvas from "react-signature-canvas";
import toast from "react-hot-toast";

const StepOnboarding = ({ nextStep, prevStep }) => {
  const stepList = [
    { key: "mobile", label: "Mobile Verification" },
    { key: "email", label: "Email Verification" },
    { key: "id", label: "ID Verification" },
    { key: "signature", label: "Signature Verification" },
    { key: "store", label: "Store & Pickup Details" },
    { key: "listing", label: "Listing Created" },
  ];

  
  const sectionRefs = useRef({});
  stepList.forEach((item) => {
    if (!sectionRefs.current[item.key]) {
      sectionRefs.current[item.key] = React.createRef();
    }
  });

  const [steps, setSteps] = useState({
    mobile: true,
    email: true,
    id: false,
    signature: false,
    store: false,
    listing: false,
  });

  const [formData, setFormData] = useState({
    displayName: "",
    storeName: "",
    storeDescription: "",
    pinCode: "",
    listing: "",
  });

  const [idFile, setIdFile] = useState(null);
  const [showDraw, setShowDraw] = useState(false);
  const [showUpload, setShowUpload] = useState(false);
  const sigCanvas = useRef(null);

  const progress =
    (Object.values(steps).filter(Boolean).length / Object.keys(steps).length) *
    100;

  const handleStepComplete = (key) => {
    setSteps((prev) => {
      const updated = { ...prev, [key]: true };
      const stepKeys = Object.keys(updated);
      const nextIndex = stepKeys.indexOf(key) + 1;
      if (nextIndex < stepKeys.length) {
        const nextKey = stepKeys[nextIndex];
        sectionRefs.current[nextKey]?.current?.scrollIntoView({
          behavior: "smooth",
          block: "start",
        });
      }
      return updated;
    });
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => {
      const updated = { ...prev, [name]: value };

      const { displayName, storeName, storeDescription, pinCode } = updated;
      if (displayName && storeName && storeDescription && pinCode) {
        handleStepComplete("store");
      }

      if (name === "listing" && value.trim()) {
        handleStepComplete("listing");
      }

      return updated;
    });
  };

  const handleIdUpload = (e) => {
    const file = e.target.files[0];
    if (file) {
      setIdFile(file);
      handleStepComplete("id");
      toast.success("ID uploaded successfully!");
    }
  };

  const saveDrawSignature = () => {
    if (!sigCanvas.current || sigCanvas.current.isEmpty()) {
      toast.error("Please draw your signature first.");
      return;
    }
    handleStepComplete("signature");
    toast.success("Signature saved!");
  };

  const clearDrawSignature = () => {
    sigCanvas.current?.clear();
    setSteps((prev) => ({ ...prev, signature: false }));
    toast("Signature cleared.", { icon: "✏️" });
  };

  const allCompleted = Object.values(steps).every(Boolean);

  return (
    <div className="min-h-screen bg-gray-50 flex justify-center py-10 px-4 overflow-hidden">
      <div className="flex flex-col lg:flex-row w-full max-w-7xl gap-8">
        {/* ===== Sidebar ===== */}
        <aside className="w-64 bg-white border border-orange-300 rounded-lg p-5 shadow-sm self-start sticky top-4 h-fit animate-fadeIn">
          <h3 className="font-semibold mb-3 text-gray-700 text-sm">
            Onboarding Status
          </h3>

          <div className="mb-4">
            <div className="w-full bg-gray-200 rounded-full h-2 overflow-hidden">
              <div
                className="bg-orange-500 h-2 rounded-full transition-all duration-500"
                style={{ width: `${progress}%` }}
              />
            </div>
            <p className="text-xs text-gray-500 mt-1 text-center">
              {Math.round(progress)}% completed
            </p>
          </div>

          <div className="flex flex-col space-y-1 text-sm">
            {stepList.map((item, index) => (
              <div
                key={item.key}
                className={`flex items-center gap-2 px-2 py-1 rounded-md transition-colors duration-300 ${
                  steps[item.key]
                    ? "text-orange-600 font-medium"
                    : "text-gray-500"
                }`}
              >
                <span
                  className={`w-5 h-5 flex items-center justify-center rounded-full border-2 text-xs font-semibold transition-all duration-300 ${
                    steps[item.key]
                      ? "bg-orange-500 text-white border-orange-500"
                      : "border-gray-400 text-gray-400"
                  }`}
                >
                  {index + 1}
                </span>
                {item.label}
              </div>
            ))}
          </div>
        </aside>

        {/* ===== Main Content ===== */}
        <main className="flex-1 space-y-6 overflow-y-auto max-h-[85vh] pr-2 scroll-smooth scrollbar-hide animate-fadeIn">
          {/* Mobile Verification */}
          <section
            ref={sectionRefs.current.mobile}
            className="bg-white p-4 rounded-lg shadow-sm"
          >
            <h3 className="font-medium mb-2 text-gray-800">
              Mobile Verification <span className="text-red-500">*</span>
            </h3>
            <p className="text-gray-600">+91 8792153479 ✅</p>
          </section>

          {/* Email Verification */}
          <section
            ref={sectionRefs.current.email}
            className="bg-white p-4 rounded-lg shadow-sm"
          >
            <h3 className="font-medium mb-2 text-gray-800">
              Email Verification <span className="text-red-500">*</span>
            </h3>
            <p className="text-gray-600">vishruthareddy481@gmail.com ✅</p>
          </section>

          {/* ID Verification */}
          <section
            ref={sectionRefs.current.id}
            className="bg-white p-4 rounded-lg shadow-sm"
          >
            <h3 className="font-medium mb-2 text-gray-800">
              ID Verification <span className="text-red-500">*</span>
            </h3>
            <input
              type="file"
              accept="image/*,.pdf"
              onChange={handleIdUpload}
              className="w-full border p-1 rounded-md text-sm"
              required
            />
            {idFile && (
              <p className="text-green-600 text-sm mt-2">
                {idFile.name} uploaded successfully
              </p>
            )}
          </section>

          {/* Signature Verification */}
          <section
            ref={sectionRefs.current.signature}
            className="bg-white p-4 rounded-lg shadow-sm"
          >
            <h3 className="font-medium mb-3 text-gray-800">
              Signature Verification <span className="text-red-500">*</span>
            </h3>

            <div className="flex gap-3 mb-4">
              <button
                onClick={() => {
                  setShowDraw(true);
                  setShowUpload(false);
                }}
                className={`px-3 py-1 rounded-md text-sm font-medium ${
                  showDraw
                    ? "bg-orange-500 text-white"
                    : "bg-gray-200 text-gray-700 hover:bg-gray-300"
                }`}
              >
                ✏️ Draw
              </button>
              <button
                onClick={() => {
                  setShowDraw(false);
                  setShowUpload(true);
                }}
                className={`px-3 py-1 rounded-md text-sm font-medium ${
                  showUpload
                    ? "bg-orange-500 text-white"
                    : "bg-gray-200 text-gray-700 hover:bg-gray-300"
                }`}
              >
                📤 Upload
              </button>
            </div>

            {showDraw && (
              <div className="border-2 border-gray-300 rounded-lg mb-2 bg-gray-50">
                <SignatureCanvas
                  ref={sigCanvas}
                  penColor="orange"
                  canvasProps={{
                    width: 350,
                    height: 100,
                    className: "bg-gray-50 rounded-lg w-full h-24",
                  }}
                />
              </div>
            )}

            <div className="flex gap-3 mb-2">
              {showDraw && (
                <>
                  <button
                    onClick={saveDrawSignature}
                    className="px-3 py-1 bg-orange-500 text-white rounded-md hover:bg-orange-600 text-sm"
                  >
                    Save
                  </button>
                  <button
                    onClick={clearDrawSignature}
                    className="px-3 py-1 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 text-sm"
                  >
                    Clear
                  </button>
                </>
              )}

              {showUpload && (
                <button
                  onClick={() => {
                    handleStepComplete("signature");
                    toast.success("Signature uploaded successfully!");
                  }}
                  className="px-3 py-1 bg-orange-500 text-white rounded-md hover:bg-orange-600 text-sm"
                >
                  Save Upload
                </button>
              )}
            </div>
          </section>

          {/* Store & Pickup Details */}
          <section
            ref={sectionRefs.current.store}
            className="bg-white p-4 rounded-lg shadow-sm"
          >
            <h3 className="font-medium mb-3 text-gray-800">
              Store & Pickup Details <span className="text-red-500">*</span>
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
              <input
                type="text"
                name="storeName"
                value={formData.storeName}
                onChange={handleInputChange}
                placeholder="Store Name *"
                className="border p-1 rounded-md text-sm"
              />
              <input
                type="text"
                name="displayName"
                value={formData.displayName}
                onChange={handleInputChange}
                placeholder="Display Name *"
                className="border p-1 rounded-md text-sm"
              />
              <textarea
                name="storeDescription"
                value={formData.storeDescription}
                onChange={handleInputChange}
                placeholder="Store Description *"
                rows="3"
                className="border p-1 rounded-md text-sm col-span-2"
              ></textarea>
              <input
                type="text"
                name="pinCode"
                value={formData.pinCode}
                onChange={handleInputChange}
                placeholder="Pin Code *"
                className="border p-1 rounded-md text-sm"
              />
            </div>
            <button
              onClick={() => {
                const { storeName, displayName, storeDescription, pinCode } =
                  formData;
                if (storeName && displayName && storeDescription && pinCode) {
                  handleStepComplete("store");
                  toast.success("Store details saved!");
                } else {
                  toast.error("Please fill all fields.");
                }
              }}
              className="mt-3 px-4 py-1 bg-orange-500 text-white rounded-md hover:bg-orange-600 text-sm"
            >
              Save
            </button>
          </section>

          {/* Listing Created */}
          <section
            ref={sectionRefs.current.listing}
            className="bg-white p-4 rounded-lg shadow-sm"
          >
            <h3 className="font-medium mb-2 text-gray-800">
              Listing Created <span className="text-red-500">*</span>
            </h3>
            <input
              type="text"
              name="listing"
              value={formData.listing}
              onChange={handleInputChange}
              placeholder="Enter listing name or ID *"
              className="w-full border p-1 rounded-md text-sm"
            />
          </section>

          {/* Navigation Buttons */}
          <div className="flex justify-between mt-4">
            <button
              onClick={prevStep}
              className="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 text-sm"
            >
              ← Back
            </button>
            <button
              onClick={() => allCompleted && nextStep()}
              disabled={!allCompleted}
              className={`px-4 py-2 rounded-md text-white text-sm ${
                allCompleted
                  ? "bg-orange-500 hover:bg-orange-600"
                  : "bg-orange-300 cursor-not-allowed"
              }`}
            >
              Submit
            </button>
          </div>
        </main>
      </div>
    </div>
  );
};

export default StepOnboarding;
