"use client";

import { useEffect, useState } from "react";
import { ArrowUpRight } from "lucide-react";
import { useAuth } from "../hooks/useAuth";

interface Props {
  data: any;
  loading: boolean;
  onSave: (data: any) => Promise<any>;
  onSaveDraft: (data: any) => Promise<any>;
}

export default function StepAccount({ data, loading, onSave }: Props) {
  const auth = useAuth();

  const [phone, setPhone] = useState(data?.phone ?? "");
  const [otp, setOtp] = useState("");
  const [otpSent, setOtpSent] = useState(false);
  const [sending, setSending] = useState(false);

  useEffect(() => {
    if (auth.user?.phone && !data?.phone) {
      setPhone(auth.user.phone);
    }
  }, [auth.user?.phone, data?.phone]);

  if (auth.loading) {
    return (
      <div className="py-8 text-center font-inter text-sm text-muted">
        Loading account...
      </div>
    );
  }

  const alreadyVerified = auth.isAuthenticated && !!auth.user?.phone;

  const sendOtp = async () => {
    if (phone.length < 9) return;
    setSending(true);
    try {
      const { api } = await import("@/lib/api-client");
      await api.auth.requestOtp(phone);
      setOtpSent(true);
    } catch {
      // handled by parent error state
    } finally {
      setSending(false);
    }
  };

  const continueAsAuthenticated = async () => {
    if (!auth.user?.phone) return;
    await onSave({ phone: auth.user.phone, verified: true });
  };

  const verifyAndContinue = async () => {
    if (otp.length < 4) return;
    try {
      const { api } = await import("@/lib/api-client");
      await api.auth.verify(phone, otp);
      await auth.checkAuth();
      await onSave({ phone, verified: true });
    } catch {
      // handled by parent
    }
  };

  if (alreadyVerified) {
    return (
      <div className="space-y-5">
        <div>
          <h2 className="font-onest text-2xl font-semibold text-ink">Create your account</h2>
          <p className="mt-1 font-inter text-sm text-ink-soft">
            Your phone number is already verified. Continue to the next step.
          </p>
        </div>

        <div>
          <label htmlFor="phone" className="block font-inter text-sm font-medium text-ink-soft mb-1.5">
            Phone Number
          </label>
          <input
            id="phone"
            type="tel"
            value={auth.user?.phone ?? phone}
            readOnly
            className="w-full px-4 py-3 rounded-xl border border-border bg-surface-elevated font-inter text-sm text-ink cursor-not-allowed"
          />
        </div>

        <button
          onClick={continueAsAuthenticated}
          disabled={loading}
          className="w-full flex items-center justify-center gap-2 py-3.5 rounded-full bg-green-deep text-white font-inter font-medium text-base hover:bg-green-deep/90 transition-colors disabled:opacity-50 cursor-pointer"
        >
          {loading ? "Continuing..." : "Continue"}
          <ArrowUpRight className="w-4 h-4" />
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-5">
      <div>
        <h2 className="font-onest text-2xl font-semibold text-ink">Create your account</h2>
        <p className="mt-1 font-inter text-sm text-ink-soft">
          Enter your phone number to get started with the pilot program.
        </p>
      </div>

      <div>
        <label htmlFor="phone" className="block font-inter text-sm font-medium text-ink-soft mb-1.5">
          Phone Number
        </label>
        <input
          id="phone"
          type="tel"
          placeholder="+998 XX XXX XX XX"
          value={phone}
          onChange={(e) => setPhone(e.target.value)}
          disabled={otpSent}
          className="w-full px-4 py-3 rounded-xl border border-border bg-surface font-inter text-sm text-ink placeholder:text-muted/70 focus:outline-none focus:border-green-deep/40 focus:ring-1 focus:ring-green-deep/20 transition-colors disabled:opacity-50"
        />
      </div>

      {!otpSent ? (
        <button
          onClick={sendOtp}
          disabled={phone.length < 9 || sending || loading}
          className="w-full flex items-center justify-center gap-2 py-3.5 rounded-full bg-green-deep text-white font-inter font-medium text-base hover:bg-green-deep/90 transition-colors disabled:opacity-50 cursor-pointer"
        >
          {sending ? "Sending..." : "Send OTP"}
          <ArrowUpRight className="w-4 h-4" />
        </button>
      ) : (
        <>
          <div>
            <label htmlFor="otp" className="block font-inter text-sm font-medium text-ink-soft mb-1.5">
              Enter OTP
            </label>
            <input
              id="otp"
              type="text"
              maxLength={4}
              placeholder="1234"
              value={otp}
              onChange={(e) => setOtp(e.target.value)}
              className="w-full px-4 py-3 rounded-xl border border-border bg-surface font-inter text-sm text-ink placeholder:text-muted/70 focus:outline-none focus:border-green-deep/40 focus:ring-1 focus:ring-green-deep/20 transition-colors tracking-widest text-center"
            />
            <p className="mt-1 text-xs text-muted font-inter">
              In development, use code: 1234
            </p>
          </div>
          <button
            onClick={verifyAndContinue}
            disabled={otp.length < 4 || loading}
            className="w-full flex items-center justify-center gap-2 py-3.5 rounded-full bg-green-deep text-white font-inter font-medium text-base hover:bg-green-deep/90 transition-colors disabled:opacity-50 cursor-pointer"
          >
            {loading ? "Verifying..." : "Verify & Continue"}
            <ArrowUpRight className="w-4 h-4" />
          </button>
          <button
            onClick={() => { setOtpSent(false); setOtp(""); }}
            className="w-full text-center font-inter text-sm text-green-deep hover:underline cursor-pointer"
          >
            Change phone number
          </button>
        </>
      )}
    </div>
  );
}
