"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import Header from "@/app/components/layout/Header";
import Footer from "@/app/components/layout/Footer";
import StepShell from "@/app/components/astrologer/StepShell";
import {
  getMasterDocumentTypes,
  uploadAstrologerDocument,
  friendlyErrorMessage,
} from "@/app/lib/astrologer";

interface DocType {
  id: number;
  name: string;
  code: string;
  is_required: boolean;
}

interface DocCategory {
  master_type: string;
  document_types: DocType[];
}

// Confirmed live against the real backend: `master/document-types`
// returns { data: [{ master_type, document_types: [{id, name, code,
// is_required}] }] } — master types (Adharcard, Pancard, Bank, Skills,
// Education...) and their document codes come from here, not guessed.
function extractCategories(response: any): DocCategory[] {
  const list = response?.data ?? response ?? [];
  return Array.isArray(list) ? list : [];
}

// Nicer labels for the master-type dropdown — falls back to the raw
// master_type string for anything the backend adds later.
const MASTER_TYPE_LABELS: Record<string, string> = {
  Adharcard: "Aadhar Card",
  Pancard: "Pancard",
  Bank: "Bank",
  Skills: "Skills",
  Education: "Education",
};

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

  const [categories, setCategories] = useState<DocCategory[]>([]);
  const [fetching, setFetching] = useState(true);
  const [loading, setLoading] = useState(false);

  const [selectedMasterType, setSelectedMasterType] = useState("");
  const [selectedDocCode, setSelectedDocCode] = useState("");
  const [documentNumber, setDocumentNumber] = useState("");
  const [file, setFile] = useState<File | null>(null);
  const [uploading, setUploading] = useState(false);

  // Confirmed live: every document upload response carries
  // `is_kyc_doc_updated` / `kyc_message` / `pending_documents`,
  // telling us exactly what's still missing — drive the on-page
  // status message from that instead of guessing which docs are
  // "required" from the master list alone.
  const [kycMessage, setKycMessage] = useState<string | null>(null);
  const [isKycComplete, setIsKycComplete] = useState(false);
  const [showOptionalModal, setShowOptionalModal] = useState(false);

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

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

    getMasterDocumentTypes(token)
      .then((response) => setCategories(extractCategories(response)))
      .catch(() => toast.error("Unable to load document requirements."))
      .finally(() => setFetching(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const selectedCategory = categories.find(
    (c) => c.master_type === selectedMasterType
  );
  const docOptions = selectedCategory?.document_types ?? [];

  const handleMasterTypeChange = (value: string) => {
    setSelectedMasterType(value);
    setDocumentNumber("");
    setFile(null);

    const category = categories.find((c) => c.master_type === value);

    // Auto-pick the document type when a category only offers one
    // (matches the real Aadhar Card / Pancard categories today).
    setSelectedDocCode(
      category?.document_types.length === 1
        ? category.document_types[0].code
        : ""
    );
  };

  const handleUpload = async () => {
    if (!selectedMasterType || !selectedDocCode) {
      toast.error("Choose a document type first");
      return;
    }

    if (!documentNumber.trim()) {
      toast.error("Enter the document ID number");
      return;
    }

    if (!file) {
      toast.error("Please choose a file to upload");
      return;
    }

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

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

    try {
      setUploading(true);

      const response = await uploadAstrologerDocument(
        {
          file,
          documentType: selectedDocCode,
          documentNumber,
          masterType: selectedMasterType,
        },
        token
      );

      if (!response.success) {
        toast.error(friendlyErrorMessage(response.message, "Upload failed"));
        return;
      }

      toast.success("Document uploaded");

      const data = response.data ?? {};
      const kycUpdated = !!data.is_kyc_doc_updated;

      setKycMessage(data.kyc_message ?? null);

      // Reset the form so the next category can be picked.
      setSelectedMasterType("");
      setSelectedDocCode("");
      setDocumentNumber("");
      setFile(null);

      if (kycUpdated && !isKycComplete) {
        // KYC just became complete this upload — offer the optional
        // Education/Skills documents before moving on.
        setShowOptionalModal(true);
      }

      setIsKycComplete((prev) => prev || kycUpdated);
    } catch (error: any) {
      toast.error(
        friendlyErrorMessage(
          error.response?.data?.message,
          "Unable to upload the document."
        )
      );
    } finally {
      setUploading(false);
    }
  };

  const goNext = () => router.push("/astrologer/profile/progress");

  const handleContinue = () => {
    if (!isKycComplete) {
      toast.error("Please complete the required KYC documents first");
      return;
    }

    setLoading(true);
    goNext();
  };

  return (
    <>
    <Header />
    <StepShell step={9} title="KYC & Documents" loading={loading} onSave={handleContinue}>
      <div className="astrologer-repeat-card mb-4">
        Choose a document category below, attach the file, and submit
        — one document at a time.
      </div>

      {kycMessage && (
        <div
          className={`astrologer-kyc-alert ${
            isKycComplete ? "is-complete" : "is-pending"
          }`}
        >
          {kycMessage}
        </div>
      )}

      {fetching ? (
        <p className="terms-text-color">Loading document requirements...</p>
      ) : (
        <>
          <div className="mb-3">
            <label className="form-label fw-semibold">
              Document category
            </label>
            <select
              className="form-control form-control-lg"
              value={selectedMasterType}
              onChange={(e) => handleMasterTypeChange(e.target.value)}
            >
              <option value="">Select document type</option>
              {categories.map((c) => (
                <option key={c.master_type} value={c.master_type}>
                  {MASTER_TYPE_LABELS[c.master_type] ?? c.master_type}
                </option>
              ))}
            </select>
          </div>

          {selectedMasterType && docOptions.length > 1 && (
            <div className="mb-3">
              <label className="form-label fw-semibold">Document</label>
              <select
                className="form-control form-control-lg"
                value={selectedDocCode}
                onChange={(e) => setSelectedDocCode(e.target.value)}
              >
                <option value="">Select document</option>
                {docOptions.map((d) => (
                  <option key={d.code} value={d.code}>
                    {d.name}
                  </option>
                ))}
              </select>
            </div>
          )}

          {selectedMasterType && selectedDocCode && (
            <>
              <div className="mb-3">
                <label className="form-label fw-semibold">
                  Document ID number
                </label>
                <input
                  className="form-control form-control-lg"
                  value={documentNumber}
                  onChange={(e) => setDocumentNumber(e.target.value)}
                />
              </div>

              <div className="mb-3">
                <label className="form-label fw-semibold">
                  Upload file
                </label>
                <input
                  type="file"
                  accept="image/*,application/pdf"
                  className="form-control form-control-lg"
                  onChange={(e) => setFile(e.target.files?.[0] ?? null)}
                />
                <small className="terms-text-color">
                  JPG, PNG or PDF · Max size 5MB
                </small>
              </div>

              <button
                type="button"
                className="btn btn-primary w-100 mb-4"
                onClick={handleUpload}
                disabled={uploading}
              >
                {uploading ? "Uploading..." : "Submit document"}
              </button>
            </>
          )}
        </>
      )}

      {showOptionalModal && (
        <div className="astrologer-modal-backdrop">
          <div className="astrologer-modal">
            <h5 className="mb-2">KYC documents complete</h5>
            <p className="terms-text-color">
              Would you like to upload more documents, like Education
              or Skills certificates?
            </p>
            <div className="d-flex gap-3 mt-3">
              <button
                type="button"
                className="btn btn-outline-light flex-fill"
                onClick={() => {
                  setShowOptionalModal(false);
                  goNext();
                }}
              >
                No
              </button>
              <button
                type="button"
                className="btn btn-primary flex-fill"
                onClick={() => setShowOptionalModal(false)}
              >
                Yes
              </button>
            </div>
          </div>
        </div>
      )}
    </StepShell>
    <Footer />
    </>
  );
}
