/**
 * ProfilePage — real My Profile form, wired to backend.
 * Supports all 13 roles. Tabs: Basic Info · Documents.
 * User fills and saves freely; "Submit for Verification" locks and queues for admin.
 */
import { For, Match, Show, Switch, createEffect, createSignal, onMount } from "solid-js";
import {
  CARD,
  BTN_ORANGE,
  BTN_GHOST,
  INPUT,
  LABEL,
  BTN_PRIMARY,
} from "~/components/DashboardShell";

const API = "/api/gateway";

// ── Role-specific field definitions ──────────────────────────────────────────

const BASIC_FIELDS: Record<
  string,
  Array<{ key: string; label: string; type?: string; required?: boolean; options?: string[] }>
> = {
  default: [
    { key: "first_name", label: "First Name", required: true },
    { key: "last_name", label: "Last Name", required: true },
    { key: "phone", label: "Mobile Number", required: true },
    {
      key: "gender",
      label: "Gender",
      type: "select",
      options: ["Male", "Female", "Other", "Prefer not to say"],
    },
    { key: "location", label: "City", required: true },
    { key: "state", label: "State", required: true },
    { key: "pin_code", label: "PIN Code" },
    { key: "address", label: "Address", type: "textarea" },
  ],
  COMPANY: [
    { key: "company_name", label: "Company Name", required: true },
    { key: "company_email", label: "Company Email", type: "email", required: true },
    { key: "company_phone", label: "Company Phone" },
    { key: "website", label: "Website URL", type: "url" },
    { key: "location", label: "City", required: true },
    { key: "state", label: "State", required: true },
    { key: "pin_code", label: "PIN Code" },
    { key: "address", label: "Registered Address", type: "textarea" },
    { key: "gst_number", label: "GST Number (optional)" },
  ],
  PHOTOGRAPHER: [
    { key: "first_name", label: "First Name", required: true },
    { key: "last_name", label: "Last Name", required: true },
    { key: "phone", label: "Mobile Number", required: true },
    { key: "location", label: "City", required: true },
    { key: "state", label: "State", required: true },
    { key: "pin_code", label: "PIN Code" },
    {
      key: "speciality",
      label: "Photography Speciality",
      type: "select",
      options: [
        "Wedding",
        "Portrait",
        "Commercial",
        "Event",
        "Wildlife",
        "Fashion",
        "Product",
        "Other",
      ],
    },
    { key: "experience_years", label: "Years of Experience", type: "number" },
    { key: "bio", label: "Short Bio", type: "textarea" },
  ],
  FITNESS_TRAINER: [
    { key: "first_name", label: "First Name", required: true },
    { key: "last_name", label: "Last Name", required: true },
    { key: "phone", label: "Mobile Number", required: true },
    { key: "location", label: "City", required: true },
    { key: "state", label: "State", required: true },
    {
      key: "training_type",
      label: "Training Type",
      type: "select",
      options: [
        "Personal Training",
        "Group Fitness",
        "Yoga",
        "CrossFit",
        "Zumba",
        "Pilates",
        "Other",
      ],
    },
    { key: "experience_years", label: "Years of Experience", type: "number" },
    { key: "bio", label: "Short Bio", type: "textarea" },
  ],
  TUTOR: [
    { key: "first_name", label: "First Name", required: true },
    { key: "last_name", label: "Last Name", required: true },
    { key: "phone", label: "Mobile Number", required: true },
    { key: "location", label: "City", required: true },
    { key: "state", label: "State", required: true },
    { key: "subjects", label: "Subjects Taught (comma separated)" },
    { key: "experience_years", label: "Years of Experience", type: "number" },
    { key: "bio", label: "Short Bio", type: "textarea" },
  ],
  CATERING_SERVICES: [
    { key: "business_name", label: "Business Name", required: true },
    { key: "owner_name", label: "Owner Name", required: true },
    { key: "phone", label: "Contact Number", required: true },
    { key: "location", label: "City", required: true },
    { key: "state", label: "State", required: true },
    { key: "cuisine_types", label: "Cuisine Types (comma separated)" },
    { key: "bio", label: "About Your Service", type: "textarea" },
  ],
};

const DOC_FIELDS: Record<
  string,
  Array<{ key: string; label: string; required?: boolean; hint?: string }>
> = {
  default: [
    {
      key: "aadhar_doc",
      label: "Aadhar / Government ID",
      required: true,
      hint: "JPG, PNG or PDF · Max 10MB",
    },
  ],
  COMPANY: [
    {
      key: "registration_doc",
      label: "Company Registration Certificate",
      required: true,
      hint: "JPG, PNG or PDF · Max 10MB",
    },
    { key: "gst_doc", label: "GST Certificate (optional)", hint: "JPG, PNG or PDF · Max 10MB" },
  ],
  PHOTOGRAPHER: [
    {
      key: "aadhar_doc",
      label: "Aadhar / Government ID",
      required: true,
      hint: "JPG, PNG or PDF · Max 10MB",
    },
    {
      key: "sample_work",
      label: "Sample Work Photos (2–3 images)",
      required: true,
      hint: "JPG or PNG · Max 5MB each",
    },
  ],
  MAKEUP_ARTIST: [
    {
      key: "aadhar_doc",
      label: "Aadhar / Government ID",
      required: true,
      hint: "JPG, PNG or PDF · Max 10MB",
    },
    {
      key: "sample_work",
      label: "Sample Work Photos (2–3 images)",
      required: true,
      hint: "JPG or PNG · Max 5MB each",
    },
  ],
  TUTOR: [
    {
      key: "aadhar_doc",
      label: "Aadhar / Government ID",
      required: true,
      hint: "JPG, PNG or PDF · Max 10MB",
    },
    {
      key: "degree_certificate",
      label: "Degree Certificate",
      required: true,
      hint: "JPG, PNG or PDF · Max 10MB",
    },
  ],
  FITNESS_TRAINER: [
    {
      key: "aadhar_doc",
      label: "Aadhar / Government ID",
      required: true,
      hint: "JPG, PNG or PDF · Max 10MB",
    },
    {
      key: "certification_doc",
      label: "Fitness Certification",
      required: true,
      hint: "JPG, PNG or PDF · Max 10MB",
    },
  ],
  CATERING_SERVICES: [
    {
      key: "aadhar_doc",
      label: "Aadhar / Government ID",
      required: true,
      hint: "JPG, PNG or PDF · Max 10MB",
    },
    {
      key: "fssai_license",
      label: "FSSAI License",
      required: true,
      hint: "JPG, PNG or PDF · Max 10MB",
    },
  ],
};

function getBasicFields(roleKey: string) {
  return BASIC_FIELDS[roleKey] ?? BASIC_FIELDS.default;
}
function getDocFields(roleKey: string) {
  return DOC_FIELDS[roleKey] ?? DOC_FIELDS.default;
}

// ── Helpers ───────────────────────────────────────────────────────────────────

async function apiFetch(path: string, opts?: RequestInit) {
  return fetch(`${API}${path}`, {
    ...opts,
    credentials: "include",
    headers: { "Content-Type": "application/json", ...(opts?.headers ?? {}) },
  });
}

// ── Component ─────────────────────────────────────────────────────────────────

interface Props {
  roleKey: string;
}

type Tab = "basic" | "documents";

export default function ProfilePage(props: Props) {
  const [tab, setTab] = createSignal<Tab>("basic");
  const [form, setForm] = createSignal<Record<string, string>>({});
  const [saving, setSaving] = createSignal(false);
  const [saveMsg, setSaveMsg] = createSignal("");
  const [verificationStatus, setVerificationStatus] = createSignal("NOT_SUBMITTED");
  const [docRequest, setDocRequest] = createSignal<string | null>(null);
  const [submitting, setSubmitting] = createSignal(false);
  const [submitMsg, setSubmitMsg] = createSignal("");

  // Load saved profile + verification status on mount
  onMount(async () => {
    const [profileRes, statusRes] = await Promise.all([
      apiFetch(`/api/profile?roleKey=${props.roleKey}`),
      apiFetch(`/api/me/verification-status?roleKey=${props.roleKey}`),
    ]);

    if (profileRes.ok) {
      const data = await profileRes.json();
      if (data.profile_data && typeof data.profile_data === "object") {
        const flat: Record<string, string> = {};
        for (const [k, v] of Object.entries(data.profile_data)) {
          flat[k] = String(v ?? "");
        }
        setForm(flat);
      }
    }

    if (statusRes.ok) {
      const s = await statusRes.json();
      setVerificationStatus(s.status ?? "NOT_SUBMITTED");
      setDocRequest(s.document_request ?? null);
    }
  });

  const isLocked = () => ["PENDING", "UNDER_REVIEW"].includes(verificationStatus());

  const setField = (key: string, val: string) => setForm((prev) => ({ ...prev, [key]: val }));

  const handleSave = async () => {
    setSaving(true);
    setSaveMsg("");
    try {
      const res = await apiFetch("/api/profile", {
        method: "PATCH",
        body: JSON.stringify({ roleKey: props.roleKey, profile_data: form() }),
      });
      setSaveMsg(res.ok ? "Saved successfully." : "Failed to save. Please try again.");
    } catch {
      setSaveMsg("Network error. Please try again.");
    } finally {
      setSaving(false);
      setTimeout(() => setSaveMsg(""), 3000);
    }
  };

  const handleSubmitForVerification = async () => {
    setSubmitting(true);
    setSubmitMsg("");
    try {
      const res = await apiFetch("/api/profile/submit-for-verification", {
        method: "POST",
        body: JSON.stringify({ roleKey: props.roleKey }),
      });
      const data = await res.json();
      if (res.ok) {
        setVerificationStatus("PENDING");
        setSubmitMsg("Submitted! We will review your profile and notify you.");
      } else if (res.status === 409) {
        setSubmitMsg(data.error ?? "A verification is already in progress.");
      } else {
        setSubmitMsg(data.error ?? "Submission failed. Please try again.");
      }
    } catch {
      setSubmitMsg("Network error. Please try again.");
    } finally {
      setSubmitting(false);
    }
  };

  const statusColor: Record<string, string> = {
    PENDING: "#F59E0B",
    UNDER_REVIEW: "#3B82F6",
    DOCUMENTS_REQUESTED: "#FF5E13",
    REVISION_REQUESTED: "#FF5E13",
    APPROVED: "#10B981",
    REJECTED: "#EF4444",
    NOT_SUBMITTED: "#9CA3AF",
  };

  const statusLabel: Record<string, string> = {
    PENDING: "Pending Review",
    UNDER_REVIEW: "Under Review",
    DOCUMENTS_REQUESTED: "Documents Requested",
    REVISION_REQUESTED: "Revision Requested",
    APPROVED: "Approved",
    REJECTED: "Rejected",
    NOT_SUBMITTED: "Not Submitted",
  };

  return (
    <div style={{ "max-width": "760px" }}>
      {/* ── Verification status banner ─────────────────────────────────── */}
      <div
        style={{
          ...CARD,
          "margin-bottom": "16px",
          display: "flex",
          "align-items": "center",
          "justify-content": "space-between",
          gap: "12px",
          "flex-wrap": "wrap",
        }}
      >
        <div style={{ display: "flex", "align-items": "center", gap: "10px" }}>
          <span
            style={{
              display: "inline-flex",
              "align-items": "center",
              height: "22px",
              padding: "0 10px",
              "border-radius": "999px",
              background: `${statusColor[verificationStatus()] ?? "#9CA3AF"}22`,
              color: statusColor[verificationStatus()] ?? "#9CA3AF",
              "font-size": "11px",
              "font-weight": "700",
            }}
          >
            {statusLabel[verificationStatus()] ?? verificationStatus()}
          </span>
          <Show when={docRequest()}>
            <p style={{ margin: "0", "font-size": "13px", color: "#6B7280" }}>
              <strong style={{ color: "#FF5E13" }}>Action needed:</strong> {docRequest()}
            </p>
          </Show>
        </div>
        <Show when={!isLocked() && verificationStatus() !== "APPROVED"}>
          <button
            type="button"
            onClick={handleSubmitForVerification}
            disabled={submitting()}
            style={{ ...BTN_ORANGE, opacity: submitting() ? "0.7" : "1" }}
          >
            {submitting() ? "Submitting…" : "Submit for Verification"}
          </button>
        </Show>
      </div>

      <Show when={submitMsg()}>
        <div
          style={{
            ...CARD,
            "margin-bottom": "16px",
            padding: "12px 16px",
            background: submitMsg().includes("Submitted") ? "#ECFDF5" : "#FEF2F2",
            border: `1px solid ${submitMsg().includes("Submitted") ? "#6EE7B7" : "#FECACA"}`,
            color: submitMsg().includes("Submitted") ? "#065F46" : "#B91C1C",
            "font-size": "13px",
            "font-weight": "600",
          }}
        >
          {submitMsg()}
        </div>
      </Show>

      {/* ── Tabs ──────────────────────────────────────────────────────── */}
      <div style={{ display: "flex", gap: "4px", "margin-bottom": "16px" }}>
        <For
          each={
            [
              { key: "basic", label: "Basic Information" },
              { key: "documents", label: "Documents" },
            ] as Array<{ key: Tab; label: string }>
          }
        >
          {(t) => (
            <button
              type="button"
              onClick={() => setTab(t.key)}
              style={{
                height: "36px",
                padding: "0 16px",
                "border-radius": "8px",
                border: tab() === t.key ? "1px solid #FF5E13" : "1px solid #E5E7EB",
                background: tab() === t.key ? "#FFF3EE" : "#fff",
                color: tab() === t.key ? "#FF5E13" : "#6B7280",
                "font-size": "13px",
                "font-weight": tab() === t.key ? "700" : "500",
                cursor: "pointer",
              }}
            >
              {t.label}
            </button>
          )}
        </For>
      </div>

      {/* ── Tab content ───────────────────────────────────────────────── */}
      <div style={CARD}>
        <Switch>
          {/* Basic Info */}
          <Match when={tab() === "basic"}>
            <div style={{ display: "grid", "grid-template-columns": "1fr 1fr", gap: "16px" }}>
              <For each={getBasicFields(props.roleKey)}>
                {(field) => (
                  <div style={{ "grid-column": field.type === "textarea" ? "span 2" : "span 1" }}>
                    <label style={LABEL}>
                      {field.label}
                      <Show when={field.required}>
                        <span style={{ color: "#EF4444" }}> *</span>
                      </Show>
                    </label>
                    <Switch>
                      <Match when={field.type === "textarea"}>
                        <textarea
                          rows={3}
                          disabled={isLocked()}
                          value={form()[field.key] ?? ""}
                          onInput={(e) => setField(field.key, e.currentTarget.value)}
                          style={{
                            ...INPUT,
                            height: "auto",
                            padding: "10px 12px",
                            resize: "vertical",
                            opacity: isLocked() ? "0.6" : "1",
                          }}
                        />
                      </Match>
                      <Match when={field.type === "select"}>
                        <select
                          disabled={isLocked()}
                          value={form()[field.key] ?? ""}
                          onChange={(e) => setField(field.key, e.currentTarget.value)}
                          style={{ ...INPUT, opacity: isLocked() ? "0.6" : "1" }}
                        >
                          <option value="">Select…</option>
                          <For each={field.options ?? []}>
                            {(opt) => <option value={opt}>{opt}</option>}
                          </For>
                        </select>
                      </Match>
                      <Match when={true}>
                        <input
                          type={field.type ?? "text"}
                          disabled={isLocked()}
                          value={form()[field.key] ?? ""}
                          onInput={(e) => setField(field.key, e.currentTarget.value)}
                          style={{ ...INPUT, opacity: isLocked() ? "0.6" : "1" }}
                        />
                      </Match>
                    </Switch>
                  </div>
                )}
              </For>
            </div>

            <Show when={isLocked()}>
              <p style={{ margin: "16px 0 0", "font-size": "12px", color: "#9CA3AF" }}>
                Profile is locked while verification is in progress.
              </p>
            </Show>
          </Match>

          {/* Documents */}
          <Match when={tab() === "documents"}>
            <div style={{ display: "flex", "flex-direction": "column", gap: "16px" }}>
              <For each={getDocFields(props.roleKey)}>
                {(doc) => (
                  <div
                    style={{
                      border: "1px dashed #E5E7EB",
                      "border-radius": "10px",
                      padding: "16px",
                    }}
                  >
                    <p
                      style={{
                        margin: "0",
                        "font-size": "13px",
                        "font-weight": "700",
                        color: "#111827",
                      }}
                    >
                      {doc.label}
                      <Show when={doc.required}>
                        <span style={{ color: "#EF4444" }}> *</span>
                      </Show>
                    </p>
                    <Show when={doc.hint}>
                      <p style={{ margin: "2px 0 10px", "font-size": "11px", color: "#9CA3AF" }}>
                        {doc.hint}
                      </p>
                    </Show>
                    <Show
                      when={form()[doc.key]}
                      fallback={
                        <div style={{ display: "flex", "align-items": "center", gap: "10px" }}>
                          <input
                            type="file"
                            id={`file-${doc.key}`}
                            style={{ display: "none" }}
                            disabled={isLocked()}
                            onChange={(e) => {
                              const file = e.currentTarget.files?.[0];
                              if (file) setField(doc.key, file.name);
                            }}
                          />
                          <label
                            for={`file-${doc.key}`}
                            style={{
                              ...BTN_GHOST,
                              display: "inline-flex",
                              "align-items": "center",
                              "line-height": "1",
                              opacity: isLocked() ? "0.5" : "1",
                              cursor: isLocked() ? "not-allowed" : "pointer",
                            }}
                          >
                            Choose File
                          </label>
                          <span style={{ "font-size": "12px", color: "#9CA3AF" }}>
                            No file chosen
                          </span>
                        </div>
                      }
                    >
                      <div style={{ display: "flex", "align-items": "center", gap: "10px" }}>
                        <span
                          style={{
                            "font-size": "12px",
                            "font-weight": "600",
                            color: "#10B981",
                            background: "#ECFDF5",
                            padding: "4px 10px",
                            "border-radius": "6px",
                          }}
                        >
                          ✓ {form()[doc.key]}
                        </span>
                        <Show when={!isLocked()}>
                          <button
                            type="button"
                            onClick={() => setField(doc.key, "")}
                            style={{
                              ...BTN_GHOST,
                              height: "28px",
                              "font-size": "11px",
                              padding: "0 10px",
                            }}
                          >
                            Remove
                          </button>
                        </Show>
                      </div>
                    </Show>
                  </div>
                )}
              </For>
            </div>
          </Match>
        </Switch>
      </div>

      {/* ── Save button ─────────────────────────────────────────────── */}
      <div style={{ display: "flex", "align-items": "center", gap: "12px", "margin-top": "16px" }}>
        <button
          type="button"
          onClick={handleSave}
          disabled={saving() || isLocked()}
          style={{ ...BTN_PRIMARY, opacity: saving() || isLocked() ? "0.6" : "1" }}
        >
          {saving() ? "Saving…" : "Save Changes"}
        </button>
        <Show when={saveMsg()}>
          <span
            style={{
              "font-size": "13px",
              "font-weight": "600",
              color: saveMsg().includes("success") ? "#10B981" : "#EF4444",
            }}
          >
            {saveMsg()}
          </span>
        </Show>
      </div>
    </div>
  );
}
