"use client";

import React, { useState } from "react";
import { useOnboarding } from "../context/OnboardingContext";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import {
  Building2,
  Mail,
  Phone,
  Globe,
  MapPin,
  Lock,
  ChevronLeft,
  ChevronRight,
  Loader2,
  Receipt,
  Edit2,
} from "lucide-react";
import { toast } from "sonner";

const COUNTRY_DIAL_CODES: Record<string, string> = {
  IN: "+91",
  US: "+1",
  GB: "+44",
  CA: "+1",
  AU: "+61",
  AE: "+971",
  SG: "+65",
  DEFAULT: "+1",
};

const API_BASE = process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000";

const apiFetch = async (path: string, body: object) => {
  const res = await fetch(`${API_BASE}${path}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    credentials: "include",
    body: JSON.stringify(body),
  });
  const data = await res.json();
  if (!res.ok)
    throw new Error(data?.message || `Request failed: ${res.status}`);
  return data;
};

// OTP Modal with fixed backspace functionality
const OtpModal = ({
  email,
  isOpen,
  onClose,
  onVerified,
  stateKey,
  type,
}: {
  email: string;
  isOpen: boolean;
  onClose: () => void;
  onVerified: () => void;
  stateKey: string;
  type: string;
}) => {
  const { setOtpState } = useOnboarding();
  const inputs = React.useRef<(HTMLInputElement | null)[]>([]);
  const [otp, setOtp] = useState("");
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const timerRef = React.useRef<NodeJS.Timeout | null>(null);

  React.useEffect(() => {
    if (isOpen) {
      setOtp("");
      setTimeout(() => inputs.current[0]?.focus(), 100);
    }
  }, [isOpen]);
  
  React.useEffect(
    () => () => {
      if (timerRef.current) clearInterval(timerRef.current);
    },
    [],
  );

  const startCountdown = () => {
    setCountdown(60);
    timerRef.current = setInterval(() => {
      setCountdown((p) => {
        if (p <= 1) {
          clearInterval(timerRef.current!);
          return 0;
        }
        return p - 1;
      });
    }, 1000);
  };

  const resendOtp = async () => {
    setLoading(true);
    try {
      const data = await apiFetch("/otp/send-otp", { email, type });
      if (data.success) {
        toast.success(`OTP resent to ${email}`);
        startCountdown();
      } else toast.error(data.message || "Failed to resend");
    } catch (e: any) {
      toast.error(e.message || "Failed");
    } finally {
      setLoading(false);
    }
  };

  const verifyOtp = async () => {
    if (otp.length < 6) {
      toast.error("Enter all 6 digits");
      return;
    }
    setLoading(true);
    try {
      const data = await apiFetch("/otp/verify-otp", { email, otp, type });
      if (data.success) {
        toast.success("Email verified! ✅");
        setOtpState(stateKey, { verified: true, loading: false, otp });
        onVerified();
        onClose();
      } else {
        toast.error(data.message || "Invalid OTP");
        setOtp("");
        inputs.current[0]?.focus();
      }
    } catch (e: any) {
      toast.error(e.message || "Verification failed");
    } finally {
      setLoading(false);
    }
  };

  const handleDigit = (i: number, v: string) => {
    const clean = v.replace(/\D/, "");
    
    if (clean === "") {
      // Handle backspace/delete
      const arr = otp.split("");
      arr[i] = "";
      const newOtp = arr.join("");
      setOtp(newOtp);
      if (i > 0) {
        inputs.current[i - 1]?.focus();
      }
      return;
    }
    
    // Update the OTP array with the new digit
    const arr = otp.split("");
    arr[i] = clean;
    const newOtp = arr.join("").slice(0, 6);
    setOtp(newOtp);
    
    // Move to next input if available
    if (i < 5) {
      inputs.current[i + 1]?.focus();
    }
  };

  const handleKey = (i: number, e: React.KeyboardEvent) => {
    if (e.key === "Backspace") {
      e.preventDefault();
      if (otp[i]) {
        // Clear current digit
        const arr = otp.split("");
        arr[i] = "";
        setOtp(arr.join(""));
      } else if (i > 0) {
        // Move to previous input and clear it
        inputs.current[i - 1]?.focus();
        const arr = otp.split("");
        arr[i - 1] = "";
        setOtp(arr.join(""));
      }
    }
    if (e.key === "Enter" && otp.length === 6) verifyOtp();
  };

  const handlePaste = (e: React.ClipboardEvent) => {
    const pasted = e.clipboardData
      .getData("text")
      .replace(/\D/g, "")
      .slice(0, 6);
    setOtp(pasted);
    // Focus on the last filled input or the next empty one
    if (pasted.length === 6) {
      inputs.current[5]?.focus();
    } else if (pasted.length > 0) {
      inputs.current[pasted.length - 1]?.focus();
    }
    e.preventDefault();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div
        className="absolute inset-0 bg-black/40 backdrop-blur-sm"
        onClick={onClose}
      />
      <div className="relative bg-white rounded-2xl shadow-2xl w-full max-w-sm p-7 animate-in fade-in zoom-in-95 duration-200">
        <button
          onClick={onClose}
          className="absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer transition-colors"
        >
          ✕
        </button>

        <div className="flex justify-center mb-5">
          <div className="w-16 h-16 rounded-2xl bg-blue-50 flex items-center justify-center">
            <Lock className="w-8 h-8 text-blue-600" />
          </div>
        </div>

        <h3 className="text-xl font-bold text-gray-900 text-center mb-1">
          Check Your Email
        </h3>
        <p className="text-sm text-gray-500 text-center mb-1">
          We sent a 6-digit code to
        </p>
        <p className="text-sm font-semibold text-blue-600 text-center mb-6 truncate px-4">
          {email}
        </p>

        <div className="flex justify-center gap-2 mb-6">
          {Array.from({ length: 6 }).map((_, i) => (
            <input
              key={i}
              ref={(el) => {
                inputs.current[i] = el;
              }}
              type="text"
              inputMode="numeric"
              maxLength={1}
              value={otp[i] || ""}
              disabled={loading}
              onChange={(e) => handleDigit(i, e.target.value)}
              onKeyDown={(e) => handleKey(i, e)}
              onPaste={handlePaste}
              className={cn(
                "w-11 h-12 text-center text-lg font-bold rounded-xl border-2 outline-none transition-all",
                loading
                  ? "bg-gray-50 border-gray-200 text-gray-400 cursor-not-allowed"
                  : otp[i]
                    ? "border-blue-500 bg-blue-50 text-blue-700"
                    : "border-gray-200 bg-white text-gray-900 focus:border-blue-500 focus:bg-blue-50",
              )}
            />
          ))}
        </div>

        <Button
          onClick={verifyOtp}
          disabled={otp.length < 6 || loading}
          className="w-full bg-blue-600 hover:bg-blue-700 rounded-xl font-semibold cursor-pointer mb-4 h-11"
        >
          {loading ? (
            <>
              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
              Verifying…
            </>
          ) : (
            <>Verify Code</>
          )}
        </Button>

        <p className="text-center text-xs text-gray-500">
          Didn't receive it?{" "}
          {countdown > 0 ? (
            <span className="text-gray-400">Resend in {countdown}s</span>
          ) : (
            <button
              onClick={resendOtp}
              disabled={loading}
              className="text-blue-600 font-semibold hover:underline cursor-pointer"
            >
              Resend OTP
            </button>
          )}
        </p>
      </div>
    </div>
  );
};

// Email Input with OTP and edit capability
const EmailInputWithOtp = ({
  label,
  email,
  onChange,
  disabled,
  error,
  stateKey,
  type,
}: {
  label: string;
  email: string;
  onChange: (v: string) => void;
  disabled?: boolean;
  error?: string;
  stateKey: string;
  type: string;
}) => {
  const { otpState, setOtpState } = useOnboarding();
  const state = otpState[stateKey as keyof typeof otpState] as any;
  const [modalOpen, setModalOpen] = useState(false);
  const [sending, setSending] = useState(false);
  const [isEditing, setIsEditing] = useState(false);

  const handleSendOtp = async () => {
    if (!email || !/\S+@\S+\.\S+/.test(email)) {
      toast.error(`Enter a valid ${label} email first`);
      return;
    }
    setSending(true);
    try {
      const data = await apiFetch("/otp/send-otp", { email, type });
      if (data.success) {
        toast.success(`OTP sent to ${email}`);
        setOtpState(stateKey, { sent: true, verified: false, otp: "" });
        setModalOpen(true);
      } else toast.error(data.message || "Failed to send OTP");
    } catch (e: any) {
      toast.error(e.message || "Failed to send OTP");
    } finally {
      setSending(false);
    }
  };

  const handleEditEmail = () => {
    setIsEditing(true);
    setOtpState(stateKey, { verified: false, sent: false });
  };

  const handleEmailChange = (value: string) => {
    onChange(value);
    if (state?.verified) {
      setOtpState(stateKey, { verified: false, sent: false });
    }
  };

  return (
    <>
      <div className="space-y-1.5">
        <Label className="text-sm font-semibold text-gray-700">
          {label} <span className="text-rose-500">*</span>
        </Label>

        <div className="flex gap-2">
          <div className="relative flex-1">
            <Mail className="absolute left-3 top-3.5 -translate-y-1/2 w-3.5 h-3.5 text-gray-400 pointer-events-none" />
            <Input
              type="email"
              className={cn(
                "pl-10",
                state?.verified && !isEditing
                  ? "border-emerald-400 bg-emerald-50/60 text-emerald-800"
                  : "",
                error ? "border-rose-400" : "",
              )}
              placeholder="email@example.com"
              value={email}
              disabled={disabled || (state?.verified && !isEditing)}
              onChange={(e) => handleEmailChange(e.target.value)}
            />
          </div>

          {state?.verified && !isEditing ? (
            <div className="flex items-center gap-1.5">
              <div className="flex items-center gap-1.5 px-3 py-2 rounded-xl bg-emerald-100 text-emerald-700 text-xs font-bold whitespace-nowrap border border-emerald-200">
                ✓ Verified
              </div>
              <button
                type="button"
                onClick={handleEditEmail}
                className="p-2 rounded-xl hover:bg-gray-100 text-gray-500 transition-colors cursor-pointer"
                title="Change email"
              >
                <Edit2 className="w-4 h-4" />
              </button>
            </div>
          ) : (
            <Button
              type="button"
              size="sm"
              onClick={handleSendOtp}
              disabled={sending || !email}
              className="whitespace-nowrap cursor-pointer bg-blue-600 hover:bg-blue-700 rounded-xl px-4"
            >
              {sending ? (
                <Loader2 className="w-3.5 h-3.5 animate-spin" />
              ) : state?.sent ? (
                "Resend OTP"
              ) : (
                "Send OTP"
              )}
            </Button>
          )}
        </div>

        {error && <p className="text-xs text-rose-600 font-medium">{error}</p>}

        {state?.sent && !state?.verified && !isEditing && (
          <p className="text-xs text-gray-500">
            OTP sent —{" "}
            <button
              type="button"
              onClick={() => setModalOpen(true)}
              className="text-blue-600 font-semibold hover:underline cursor-pointer"
            >
              click to enter code
            </button>
          </p>
        )}
      </div>

      <OtpModal
        email={email}
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
        onVerified={() => setIsEditing(false)}
        stateKey={stateKey}
        type={type}
      />
    </>
  );
};

const SectionCard = ({
  icon,
  title,
  children,
}: {
  icon: React.ReactNode;
  title: string;
  children: React.ReactNode;
}) => (
  <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
    <div className="flex items-center gap-3 px-6 py-4 bg-gray-50 border-b border-gray-100">
      <div className="w-8 h-8 rounded-lg bg-blue-100 flex items-center justify-center">
        {icon}
      </div>
      <h2 className="text-base font-bold text-gray-800">{title}</h2>
    </div>
    <div className="p-6">{children}</div>
  </div>
);

const Field = ({
  label,
  required,
  error,
  hint,
  children,
}: {
  label?: string;
  required?: boolean;
  error?: string;
  hint?: string;
  children: React.ReactNode;
}) => (
  <div className="space-y-1.5">
    {label && (
      <Label className="text-sm font-semibold text-gray-700">
        {label} {required && <span className="text-rose-500">*</span>}
      </Label>
    )}
    {children}
    {error && <p className="text-xs text-rose-600 font-medium">{error}</p>}
    {hint && !error && <p className="text-xs text-gray-400">{hint}</p>}
  </div>
);

export default function Step2OrganizationDetails({
  onNext,
  onBack,
}: {
  onNext: () => void;
  onBack: () => void;
}) {
  const {
    organizationData,
    setOrganizationData,
    otpState,
    validateStep2,
    locationData,
    detectingLocation,
    createLead,
    selectedPlan,
    billingPeriod,
    isValidPhoneNumber,
    formatPhoneNumber,
  } = useOnboarding();

  const [errors, setErrors] = useState<Record<string, string>>({});
  const [submitting, setSubmitting] = useState(false);

  const countryCode = locationData.country_code || "IN";

  const handleOrg = (field: string, value: string) => {
    if (field === "phone") {
      value = formatPhoneNumber(value);
    }
    setOrganizationData({ [field]: value } as any);
    setErrors((prev) => ({ ...prev, [`org_${field}`]: "" }));
  };

  const handleOrgAddress = (field: string, value: string) => {
    setOrganizationData({
      address: { ...organizationData.address, [field]: value },
    });
  };

  const localValidate = () => {
    const e: Record<string, string> = {};
    if (!organizationData.name.trim()) e.org_name = "Org Name Required";
    if (!organizationData.email.trim()) e.org_email = "Org Email Required";
    else if (!/\S+@\S+\.\S+/.test(organizationData.email))
      e.org_email = "Invalid email";
    if (!organizationData.phone.trim()) e.org_phone = "Phone Required";
    if (!organizationData.address.street.trim()) e.org_street = "Address Required";
    if (!organizationData.address.zipCode.trim()) e.org_zipCode = "Zip code is Required";
    setErrors(e);
    if (Object.keys(e).length > 0) return false;
    return validateStep2();
  };

  const handleContinue = async () => {
    if (!localValidate()) return;

    setSubmitting(true);
    try {
      const success = await createLead();
      if (success) {
        onNext();
      }
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="max-w-3xl mx-auto">
      <div className="mb-2">
        <h1 className="text-3xl font-extrabold text-gray-900 mb-1">
          Organization Details
        </h1>
        <p className="text-gray-500 text-sm">
          Tell us about your organization. This helps us set up your account
          correctly.
        </p>
      </div>

      <div className="space-y-3">
        <SectionCard
          icon={<Building2 className="w-4 h-4 text-blue-600" />}
          title="Organization Information"
        >
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
            <Field label="Organization Name" required error={errors.org_name}>
              <div className="relative">
                <Building2 className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
                <Input
                  className="pl-10"
                  placeholder="Org Name"
                  value={organizationData.name}
                  onChange={(e) => handleOrg("name", e.target.value)}
                />
              </div>
            </Field>

            <Field label="Website" required={false}>
              <div className="relative">
                <Globe className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
                <Input
                  className="pl-10"
                  type="url"
                  placeholder="https://OrgExample.com"
                  value={organizationData.website}
                  onChange={(e) => handleOrg("website", e.target.value)}
                />
              </div>
            </Field>

            {/* Email and Phone in one line */}
            <div className="sm:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-5">
              <EmailInputWithOtp
                label="Organization Email"
                email={organizationData.email}
                onChange={(v) => handleOrg("email", v)}
                error={errors.org_email}
                stateKey="orgEmail"
                type="Organization"
              />

              <Field label="Phone Number" required error={errors.org_phone}>
                <div className="flex rounded-xl border-2 border-gray-200 overflow-hidden focus-within:border-blue-500">
                  <div className="flex items-center gap-1.5 px-3 bg-gray-50 border-r border-gray-200 text-sm font-semibold text-gray-600 whitespace-nowrap">
                    <Phone className="w-3.5 h-3.5 text-gray-400" />
                    <span className="text-gray-700">
                      {COUNTRY_DIAL_CODES[
                        organizationData?.address?.country_code || countryCode
                      ] || COUNTRY_DIAL_CODES.DEFAULT}
                    </span>
                  </div>
                  <input
                    type="tel"
                    value={organizationData.phone.replace(
                      new RegExp(
                        `^\\${COUNTRY_DIAL_CODES[organizationData?.address?.country_code || countryCode] || COUNTRY_DIAL_CODES.DEFAULT}\\s?`,
                      ),
                      "",
                    )}
                    onChange={(e) =>
                      handleOrg(
                        "phone",
                        `${e.target.value.replace(/[^\d\s\-]/g, "")}`,
                      )
                    }
                    placeholder="XXXXX XXXXX"
                    className="flex-1 px-3 py-1 text-sm outline-none bg-white text-gray-900"
                  />
                </div>
              </Field>
            </div>
          </div>

          {/* Auto-detected Location with email and phone info */}
          <div className="mt-2 pt-5  b">
            <p className="text-xs font-bold text-gray-400 uppercase tracking-widest mb-3 flex items-center gap-1.5">
              <Lock className="w-3.5 h-3.5" /> Your Address Info
            </p>
            <div className="grid grid-cols-2 sm:grid-cols-5 gap-3">
              {[
                { label: "City", val: organizationData.address.city },
                { label: "State", val: organizationData.address.state },
                { label: "Country", val: locationData.country_name },
                { label: "Timezone", val: organizationData.settings.timezone },
                { label: "Currency", val: organizationData.settings.currency },
              ].map(({ label, val }) => (
                <div
                  key={label}
                  className="p-1 rounded-xl bg-blue-50 border border-blue-100 text-center"
                >
                  <p className="text-xs text-gray-400 uppercase mb-0.5">
                    {label}
                  </p>
                  <p className="font-semibold text-gray-900 text-sm truncate">
                    {val || "…"}
                  </p>
                </div>
              ))}
            </div>
            {/* Additional info showing email and phone */}
            {/* <div className="grid grid-cols-2 gap-3 mt-3">
              <div className="p-3 rounded-xl bg-gray-50 border border-gray-100">
                <p className="text-xs text-gray-400 uppercase mb-0.5">Email</p>
                <p className="font-semibold text-gray-900 text-sm truncate">
                  {organizationData.email || "Not set"}
                </p>
              </div>
              <div className="p-3 rounded-xl bg-gray-50 border border-gray-100">
                <p className="text-xs text-gray-400 uppercase mb-0.5">Phone</p>
                <p className="font-semibold text-gray-900 text-sm truncate">
                  {organizationData.phone || "Not set"}
                </p>
              </div>
            </div> */}
          </div>

          {/* Address Section */}
          <div className="pt-5 space-y-4">
            <p className="text-xs font-bold text-gray-400 uppercase tracking-widest flex items-center gap-1.5">
              <MapPin className="w-3.5 h-3.5" /> Street Address
            </p>
            <Field label="Street Address" required error={errors.org_street}>
              <div className="relative">
                <MapPin className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
                <Input
                  className="pl-10"
                  placeholder="xyz address"
                  value={organizationData.address.street}
                  onChange={(e) => handleOrgAddress("street", e.target.value)}
                />
              </div>
            </Field>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
              <Field
                label="ZIP / Postal Code"
                required
                error={errors.org_zipCode}
              >
                <Input
                  placeholder="12345"
                  value={organizationData.address.zipCode}
                  onChange={(e) => handleOrgAddress("zipCode", e.target.value)}
                />
              </Field>

              {/* GST/VAT ID field - added below zip code */}
              <Field
                label="GST / VAT ID"
                required={false}
                hint="Optional - for tax purposes"
              >
                <div className="relative">
                  <Receipt className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
                  <Input
                    className="pl-10"
                    placeholder="GSTIN / VAT Number"
                    value={organizationData.taxId || ""}
                    onChange={(e) => handleOrg("taxId", e.target.value)}
                  />
                </div>
              </Field>
            </div>
          </div>
        </SectionCard>

        {/* Navigation */}
        <div className="flex justify-between pt-2 pb-6">
          <Button
            variant="outline"
            onClick={onBack}
            className="gap-2 rounded-xl cursor-pointer"
            disabled={submitting}
          >
            <ChevronLeft className="w-4 h-4" /> Back
          </Button>
          <Button
            onClick={handleContinue}
            disabled={detectingLocation || submitting}
            className="bg-blue-600 hover:bg-blue-700 gap-2 rounded-xl px-7 shadow-lg shadow-blue-200 cursor-pointer disabled:opacity-50"
          >
            {submitting ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" /> Saving…
              </>
            ) : (
              <>
                <span>Continue to Your Details</span>{" "}
                <ChevronRight className="w-4 h-4" />
              </>
            )}
          </Button>
        </div>
      </div>
    </div>
  );
}