import { FormEvent, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import AuthShell from '@/calyx-app/pages/auth/AuthShell';
import { authService } from '@/services/auth';
import { useToast } from '@/hooks/use-toast';
import { prefetchSignin } from '@/lib/prefetch';

function scorePw(v: string): 0 | 1 | 2 | 3 | 4 {
  let s = 0;
  if (v.length >= 8) s++;
  if (/[A-Z]/.test(v)) s++;
  if (/[0-9]/.test(v)) s++;
  if (/[^A-Za-z0-9]/.test(v)) s++;
  if (v.length >= 14) s = Math.min(s + 1, 4);
  return s as 0 | 1 | 2 | 3 | 4;
}

export default function Signup() {
  const navigate = useNavigate();
  const { toast } = useToast();

  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [industry, setIndustry] = useState('');
  const [marketingOptIn, setMarketingOptIn] = useState(true);
  const [strength, setStrength] = useState<0 | 1 | 2 | 3 | 4>(0);
  const [loading, setLoading] = useState(false);
  const [googleLoading, setGoogleLoading] = useState(false);

  const handleGoogle = async () => {
    setGoogleLoading(true);
    try {
      const res = await authService.initiateGoogleAuth();
      if (res.status === 'success' && res.data?.authUrl) {
        window.location.href = res.data.authUrl;
      } else {
        toast({ title: 'Error', description: 'Failed to connect to Google.', variant: 'destructive' });
      }
    } catch (err: any) {
      toast({ title: 'Error', description: err.message || 'Failed to connect to Google.', variant: 'destructive' });
    } finally {
      setGoogleLoading(false);
    }
  };

  const onSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setLoading(true);
    try {
      // Persist industry for a later onboarding step (not part of SignupRequest DTO)
      if (industry) sessionStorage.setItem('pendingSignupIndustry', industry);
      sessionStorage.setItem('pendingMarketingOptIn', String(marketingOptIn));

      const res = await authService.signup({
        email,
        password,
        firstName,
        lastName,
        businessName: '',
        countryCode: 0,
        contactNumber: 0,
      });

      if (res.status === 'success') {
        toast({ title: 'Account created', description: res.message });
        navigate('/verify-otp', { state: { email, password, mode: 'signup' } });
      }
    } catch (err: any) {
      toast({ title: 'Sign-up failed', description: err.message || 'Something went wrong', variant: 'destructive' });
    } finally {
      setLoading(false);
    }
  };

  const disabled = loading || googleLoading;

  return (
    <AuthShell side="signup">
      <div className="auth-card auth-card--signup">
        <div className="head">
          <div className="eyebrow-mono">
            <span className="pill">Free forever</span> Create account
          </div>
          <h1>Start <em>free.</em><br />No card needed.</h1>
          <p className="lede">Ninety seconds to your first booking page. Zero if you use Google.</p>
        </div>

        <div className="sso">
          <button type="button" aria-label="Continue with Google" onClick={handleGoogle} disabled={disabled}>
            <svg width="18" height="18" viewBox="0 0 18 18" xmlns="http://www.w3.org/2000/svg">
              <path d="M17.64 9.2c0-.64-.06-1.25-.17-1.84H9v3.49h4.84a4.14 4.14 0 01-1.8 2.72v2.26h2.92c1.7-1.57 2.68-3.88 2.68-6.63z" fill="#4285F4" />
              <path d="M9 18c2.43 0 4.47-.81 5.96-2.18l-2.92-2.26c-.81.54-1.84.86-3.04.86-2.34 0-4.32-1.58-5.03-3.7H.96v2.33A9 9 0 009 18z" fill="#34A853" />
              <path d="M3.97 10.71A5.41 5.41 0 013.68 9c0-.59.1-1.17.29-1.71V4.96H.96A9 9 0 000 9c0 1.45.35 2.82.96 4.04l3.01-2.33z" fill="#FBBC05" />
              <path d="M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.58A8.97 8.97 0 009 0 9 9 0 00.96 4.96L3.97 7.3C4.68 5.16 6.66 3.58 9 3.58z" fill="#EA4335" />
            </svg>
            {googleLoading ? 'Connecting…' : 'Google'}
          </button>
          <button type="button" aria-label="Continue with Apple" disabled={disabled}>
            <svg width="16" height="18" viewBox="0 0 16 18" fill="#000" xmlns="http://www.w3.org/2000/svg">
              <path d="M13.27 9.47c-.02-2.16 1.77-3.21 1.85-3.26-1.01-1.47-2.58-1.68-3.14-1.7-1.34-.13-2.61.79-3.29.79-.69 0-1.73-.77-2.84-.75-1.46.02-2.81.85-3.56 2.15-1.52 2.63-.39 6.53 1.09 8.67.72 1.04 1.59 2.22 2.7 2.18 1.08-.04 1.5-.7 2.81-.7s1.68.7 2.83.68c1.17-.02 1.91-1.06 2.62-2.12.83-1.22 1.17-2.41 1.19-2.47-.03-.01-2.27-.87-2.3-3.45zM10.95 3.1c.59-.72.99-1.71.88-2.7-.85.03-1.88.56-2.5 1.27-.55.63-1.03 1.65-.9 2.62.95.07 1.92-.48 2.52-1.19z" />
            </svg>
            Apple
          </button>
        </div>

        <div className="divider">or with email</div>

        <form className="form-stack form-stack--14" onSubmit={onSubmit}>
          <div className="two-col">
            <div className="field">
              <label htmlFor="su-fn">First name</label>
              <input id="su-fn" type="text" placeholder="Jordan" autoComplete="given-name" required value={firstName} onChange={e => setFirstName(e.target.value)} disabled={disabled} />
            </div>
            <div className="field">
              <label htmlFor="su-ln">Last name</label>
              <input id="su-ln" type="text" placeholder="Maitland" autoComplete="family-name" required value={lastName} onChange={e => setLastName(e.target.value)} disabled={disabled} />
            </div>
          </div>

          <div className="field">
            <label htmlFor="su-email">Work email</label>
            <input id="su-email" type="email" placeholder="you@studio.co" autoComplete="email" required value={email} onChange={e => setEmail(e.target.value)} disabled={disabled} />
          </div>

          <div className="field">
            <label htmlFor="su-pw">Password</label>
            <input
              id="su-pw"
              type="password"
              placeholder="At least 8 characters"
              autoComplete="new-password"
              minLength={8}
              required
              value={password}
              onChange={e => { setPassword(e.target.value); setStrength(scorePw(e.target.value)); }}
              disabled={disabled}
            />
            <div className="pw-meter" data-s={strength}>
              <span /><span /><span /><span />
            </div>
            <div className="hint">8+ characters with a number or symbol.</div>
          </div>

          <div className="field">
            <label htmlFor="su-industry">What kind of work do you do?</label>
            <select
              id="su-industry"
              required
              value={industry}
              onChange={e => setIndustry(e.target.value)}
              disabled={disabled}
            >
              <option value="" disabled>Select one so we can tailor your setup…</option>
              <option value="therapist">Therapy · counseling</option>
              <option value="coach">Coaching · consulting</option>
              <option value="consultant">Business consulting</option>
              <option value="lawyer">Legal · consultations</option>
              <option value="salon">Salon · spa · beauty</option>
              <option value="trainer">Fitness · training</option>
              <option value="creative">Design · creative studio</option>
              <option value="other">Something else</option>
            </select>
          </div>

          <label className="checkbox-row">
            <input
              type="checkbox"
              checked={marketingOptIn}
              onChange={e => setMarketingOptIn(e.target.checked)}
              disabled={disabled}
            />
            <span>Send me occasional product updates. No newsletters, no fluff.</span>
          </label>

          <button type="submit" className="btn-primary-lg" disabled={disabled}>
            {loading ? 'Creating account…' : <>Create my booking page <span>→</span></>}
          </button>

          <div className="legal">
            By creating an account you agree to our <a href="/terms">Terms</a> and <a href="/privacy">Privacy Policy</a>.
          </div>
        </form>

        <div className="auth-alt">
          Already have an account? <a href="/signin" onMouseEnter={prefetchSignin}>Sign in</a>
        </div>
      </div>
    </AuthShell>
  );
}
