'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Mail, Lock, User, ArrowRight, ArrowLeft, Eye, EyeOff, Shield, CheckCircle2, Phone, Upload, AlertTriangle, Briefcase, DollarSign, KeyRound } from 'lucide-react';
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { authService } from '@/services/auth.service';
import { emailConfigService } from '@/services/email-config.service';
import { getErrorMessage } from '@/lib/errors';
import { getSystemEmailFallback } from '@/utils/environment';
import { useSystemConfig } from '@/hooks/useSystemConfig';

const STEPS = ['Account', 'Details', 'Verify'];

function formatVerificationCode(code: string): string {
  if (!code) return '------';
  // Handle 6-digit numeric code
  if (/^\d{6}$/.test(code)) return code;
  // Handle hex codes (legacy)
  const hex = code.replace(/[^a-fA-F0-9]/g, '').toUpperCase();
  const padded = hex.slice(0, 6).padEnd(6, '0');
  return `FASECMO-${padded}`;
}

function getPasswordStrength(pwd: string, minLen: number): { score: number; label: string; color: string } {
  if (!pwd) return { score: 0, label: '', color: '' };
  let score = 0;
  if (pwd.length >= minLen) score++;
  if (pwd.length >= minLen + 4) score++;
  if (/[A-Z]/.test(pwd)) score++;
  if (/[0-9]/.test(pwd)) score++;
  if (/[^A-Za-z0-9]/.test(pwd)) score++;

  if (score <= 2) return { score, label: 'Weak', color: 'text-red-500' };
  if (score <= 3) return { score, label: 'Fair', color: 'text-amber-500' };
  if (score <= 4) return { score, label: 'Good', color: 'text-emerald-500' };
  return { score, label: 'Strong', color: 'text-emerald-600' };
}

function isPasswordValid(pwd: string, minLen: number): boolean {
  if (!pwd || pwd.length < minLen) return false;
  if (!/[a-z]/.test(pwd)) return false;
  if (!/[A-Z]/.test(pwd)) return false;
  if (!/[0-9]/.test(pwd)) return false;
  if (!/[^A-Za-z0-9]/.test(pwd)) return false;
  return true;
}

export default function RegisterContent() {
  const router = useRouter();
  const sysConfig = useSystemConfig();
  const [step, setStep] = useState(0);
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [referralCode, setReferralCode] = useState('');
  const [jobTitle, setJobTitle] = useState('');
  const [incomeRange, setIncomeRange] = useState('');
  const [verificationEmail, setVerificationEmail] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [registrationMessage, setRegistrationMessage] = useState('');
  const [systemEmail, setSystemEmail] = useState('');
  const [screenshotFile, setScreenshotFile] = useState<File | null>(null);
  const [registrationDone, setRegistrationDone] = useState(false);
  const [requiresVerificationPage, setRequiresVerificationPage] = useState(false);
  const [uploadingScreenshot, setUploadingScreenshot] = useState(false);
  const [uploadSuccess, setUploadSuccess] = useState(false);
  const [uploadError, setUploadError] = useState<string | null>(null);

  const passwordStrength = getPasswordStrength(password, sysConfig.minPasswordLength);

  // Fetch system email and admin registration message on component mount
  useEffect(() => {
    emailConfigService
      .getActive()
      .then((config) => {
        if (config?.email) {
          setSystemEmail(config.email);
        }
      })
      .catch(() => {
        setSystemEmail(getSystemEmailFallback());
      });

    authService
      .getRegistrationMessage()
      .then((resp: any) => {
        const msg = resp?.data?.data?.message ?? resp?.data?.message;
        if (typeof msg === 'string' && msg.trim()) {
          setRegistrationMessage(msg.trim());
        }
      })
      .catch(() => {
        /* keep default empty -> fallback message in UI */
      });
  }, []);

  const handleUploadScreenshot = async () => {
    if (!screenshotFile) {
      setUploadError('Please select a screenshot to upload.');
      return;
    }
    setUploadingScreenshot(true);
    setUploadError(null);
    try {
      await authService.registerVerifyUpload(email, verificationCode, screenshotFile);
      setUploadSuccess(true);
      setScreenshotFile(null);
    } catch (err) {
      setUploadError(getErrorMessage(err));
    } finally {
      setUploadingScreenshot(false);
    }
  };

  const next = () => {
    setError(null);
    setStep((s) => Math.min(s + 1, STEPS.length - 1));
  };

  const prev = () => {
    setError(null);
    setStep((s) => Math.max(s - 1, 0));
  };

  const handleSubmit = async () => {
    setError(null);
    setSuccess(null);
    setUploadError(null);
    setLoading(true);
    try {
      const { data } = await authService.register({
        email,
        password,
        firstName: firstName || undefined,
        lastName: lastName || undefined,
        phone: phone || undefined,
        referralCode: referralCode || undefined,
        jobTitle: jobTitle || undefined,
        incomeRange: incomeRange || undefined,
        verificationEmail: verificationEmail || undefined,
      });

      setLoading(false);
       const res = data?.data ?? {};
      setVerificationCode(res?.verificationCode ?? res?.emailVerificationCode ?? '');
      setSystemEmail(res?.systemEmail ?? getSystemEmailFallback());
      setRequiresVerificationPage(res?.requiresVerificationPage ?? false);

      if (res?.requiresVerificationPage) {
        router.push('/verification');
      } else {
        setRegistrationDone(true);
        setStep(STEPS.length - 1);
        setSuccess(
          res?.message ?? data?.message ?? 'Registration successful. You can now log in.',
        );
      }
    } catch (err) {
      setError(getErrorMessage(err));
      setLoading(false);
    }
  };

  const isStep0Valid = email && isPasswordValid(password, sysConfig.minPasswordLength);
  const isStep1Valid = firstName && lastName && incomeRange;

  return (
    <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-surface-sunken px-4 py-10">
      <div className="pointer-events-none absolute inset-0">
        <div className="absolute -left-40 -top-40 h-96 w-96 rounded-full bg-primary-500/20 blur-3xl" />
        <div className="absolute -bottom-40 -right-40 h-96 w-96 rounded-full bg-indigo-500/20 blur-3xl" />
        <div className="absolute inset-0 bg-grid opacity-40" />
      </div>

      <div className="relative mx-auto w-full max-w-md">
        <div className="mb-6 text-center">
          <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-2xl bg-gradient-to-br from-primary-500 to-indigo-600 text-white">
            <Shield className="h-6 w-6" />
          </div>
          <h1 className="text-2xl font-bold text-ink">Create your account</h1>
          <p className="mt-1 text-sm text-ink-muted">Join {sysConfig.projectName} and start your journey</p>
        </div>

        {/* Admin-configured registration notice (set in System Settings) */}
        {registrationMessage && (
          <div
            className="mb-4 flex items-start gap-2 rounded-xl border border-indigo-500/30 bg-indigo-500/10 p-3 text-left text-sm text-indigo-700 dark:text-indigo-300"
            role="note"
            aria-label="Registration notice"
          >
            <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
            <span>{registrationMessage}</span>
          </div>
        )}

        {/* Step Progress */}
        <div className="mb-6">
          <div className="flex items-center justify-between">
            {STEPS.map((label, i) => (
              <div key={label} className="flex flex-1 flex-col items-center gap-2">
                <div className={`flex h-8 w-8 items-center justify-center rounded-full text-sm font-semibold transition-colors ${
                  i <= step ? 'bg-primary-600 text-white' : 'bg-surface-raised text-ink-faint border border-line'
                }`}>
                  {i < step ? <CheckCircle2 className="h-4 w-4" /> : i + 1}
                </div>
                <span className={`text-xs font-medium ${i <= step ? 'text-primary-600' : 'text-ink-faint'}`}>{label}</span>
              </div>
            ))}
          </div>
          <div className="mt-3 flex gap-1">
            {STEPS.map((_, i) => (
              <div key={i} className={`h-1 flex-1 rounded-full transition-colors ${i <= step ? 'bg-primary-600' : 'bg-surface-raised'}`} />
            ))}
          </div>
        </div>

        <Card className="card-hover">
          <CardHeader className="pb-4">
            <CardTitle className="text-xl">
              {step === 0 && 'Account Credentials'}
              {step === 1 && 'Personal Details'}
              {step === 2 && 'Email Verification'}
            </CardTitle>
            <CardDescription className="mt-1">
              {step === 0 && 'Create your login credentials'}
              {step === 1 && 'Tell us a bit about yourself'}
              {step === 2 && 'Verify your email to activate your account'}
            </CardDescription>
          </CardHeader>

          {error && (
            <div className="mx-5 mb-3 flex items-start gap-2 rounded-xl border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-600 dark:text-red-300">
              <span>{error}</span>
            </div>
          )}

          {success && step === STEPS.length - 1 && (
            <div className="mx-5 mb-3 flex items-start gap-2 rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm text-emerald-600 dark:text-emerald-300">
              <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0" />
              <span>{success}</span>
            </div>
          )}

          <CardContent className="space-y-4">
            {step === 0 && (
              <>
                <div>
                  <label htmlFor="email" className="mb-1.5 block text-sm font-medium text-ink">Email</label>
                  <Input
                    id="email"
                    type="email"
                    placeholder="you@example.com"
                    icon={<Mail className="h-4 w-4" />}
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    required
                    autoComplete="email"
                  />
                </div>
                <div>
                  <label htmlFor="password" className="mb-1.5 block text-sm font-medium text-ink">Password</label>
                  <div className="relative">
                    <Input
                      id="password"
                      type={showPassword ? 'text' : 'password'}
                      placeholder={`Min. ${sysConfig.minPasswordLength} characters`}
                      icon={<Lock className="h-4 w-4" />}
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      required
                      autoComplete="new-password"
                      className="pr-10"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword((v) => !v)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-ink-faint hover:text-ink"
                      aria-label={showPassword ? 'Hide password' : 'Show password'}
                    >
                      {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                    </button>
                  </div>
                  {password && (
                    <div className="mt-2">
                      <div className="flex items-center gap-2">
                        <div className="flex-1 h-1.5 rounded-full bg-surface-raised overflow-hidden">
                          <div className={`h-full rounded-full transition-all duration-300 ${
                            passwordStrength.score <= 2 ? 'w-1/4 bg-red-500' :
                            passwordStrength.score <= 3 ? 'w-2/4 bg-amber-500' :
                            passwordStrength.score <= 4 ? 'w-3/4 bg-emerald-500' : 'w-full bg-emerald-600'
                          }`} />
                        </div>
                        <span className={`text-xs font-medium ${passwordStrength.color}`}>{passwordStrength.label}</span>
                      </div>
                      <p className="mt-1 text-xs text-ink-faint">Use 8+ characters with uppercase, lowercase, number & special character.</p>
                    </div>
                  )}
                </div>
                <div>
                  <label htmlFor="referral" className="mb-1.5 block text-sm font-medium text-ink">Referral Code (optional)</label>
                  <div className="relative">
                    <Input
                      id="referral"
                      placeholder="ARB123"
                      icon={<KeyRound className="h-4 w-4" />}
                      value={referralCode}
                      onChange={(e) => setReferralCode(e.target.value.toUpperCase())}
                    />
                  </div>
                  <p className="mt-1 text-xs text-ink-faint">Have a referral code? Enter it here to earn bonus rewards.</p>
                </div>
              </>
            )}
            {step === 1 && (
              <>
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label htmlFor="firstName" className="mb-1.5 block text-sm font-medium text-ink">First Name</label>
                    <Input
                      id="firstName"
                      placeholder="John"
                      icon={<User className="h-4 w-4" />}
                      value={firstName}
                      onChange={(e) => setFirstName(e.target.value)}
                      autoComplete="given-name"
                    />
                  </div>
                  <div>
                    <label htmlFor="lastName" className="mb-1.5 block text-sm font-medium text-ink">Last Name</label>
                    <Input
                      id="lastName"
                      placeholder="Doe"
                      icon={<User className="h-4 w-4" />}
                      value={lastName}
                      onChange={(e) => setLastName(e.target.value)}
                      autoComplete="family-name"
                    />
                  </div>
                </div>
                <div>
                  <label htmlFor="jobTitle" className="mb-1.5 block text-sm font-medium text-ink">Job Title (optional)</label>
                  <Input
                    id="jobTitle"
                    placeholder="Software Engineer"
                    icon={<Briefcase className="h-4 w-4" />}
                    value={jobTitle}
                    onChange={(e) => setJobTitle(e.target.value)}
                  />
                </div>
                <div>
                  <label htmlFor="incomeRange" className="mb-1.5 block text-sm font-medium text-ink">Income Range <span className="text-red-500">*</span></label>
                  <div className="relative">
                    <select
                      id="incomeRange"
                      value={incomeRange}
                      onChange={(e) => setIncomeRange(e.target.value)}
                      required
                      className="flex h-10 w-full rounded-lg border border-line bg-surface-raised px-3 py-2 text-sm text-ink placeholder:text-ink-faint focus:outline-none focus:ring-2 focus:ring-primary-500 appearance-none"
                    >
                      <option value="">Select income range</option>
                      {sysConfig.incomeRanges.map((r) => (
                        <option key={r} value={r}>
                          {r}
                        </option>
                      ))}
                    </select>
                    <DollarSign className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-ink-faint pointer-events-none" />
                  </div>
                </div>
                <div>
                  <label htmlFor="phone" className="mb-1.5 block text-sm font-medium text-ink">Phone (optional)</label>
                  <Input
                    id="phone"
                    placeholder="+1 555 000 0000"
                    icon={<Phone className="h-4 w-4" />}
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                    autoComplete="tel"
                  />
                </div>
                <div>
                  <label htmlFor="verificationEmail" className="mb-1.5 block text-sm font-medium text-ink">Verification Email (optional)</label>
                  <Input
                    id="verificationEmail"
                    type="email"
                    placeholder="verify@example.com"
                    icon={<Mail className="h-4 w-4" />}
                    value={verificationEmail}
                    onChange={(e) => setVerificationEmail(e.target.value)}
                  />
                  <p className="mt-1.5 text-xs text-ink-faint">
                    We will send a verification code to this email for screenshot verification.
                  </p>
                </div>
                <div className="rounded-xl border border-blue-500/30 bg-blue-500/10 p-3">
                  <p className="text-sm text-blue-700 dark:text-blue-300">
                    <strong>System Email:</strong> After registration, send your verification code to:{' '}
                    <span className="font-semibold">{systemEmail || getSystemEmailFallback()}</span>
                  </p>
                </div>
              </>
            )}
            {step === 2 && (
              <div className="space-y-4">
                <div className="rounded-xl border border-indigo-500/30 bg-indigo-500/10 p-4">
                  <div className="flex items-start gap-2">
                    <AlertTriangle className="h-4 w-4 text-indigo-600 dark:text-indigo-300 mt-0.5 shrink-0" />
                    <p className="text-sm text-indigo-700 dark:text-indigo-200">
                      {registrationMessage ||
                        'Thank you for registering. Please follow the instructions from your administrator to complete verification.'}
                    </p>
                  </div>
                </div>

                {verificationCode && (
                  <div className="rounded-xl border border-primary-500/30 bg-primary-500/10 p-3">
                    <p className="text-xs uppercase tracking-wide text-primary-700 dark:text-primary-300">
                      Your verification code
                    </p>
                    <p className="mt-1 text-2xl font-bold tracking-widest text-primary-600 text-center py-1">
                      {formatVerificationCode(verificationCode)}
                    </p>
                    <p className="mt-1 text-xs text-ink-muted">
                      Keep this code private. Send it to the system email above, then upload a screenshot.
                    </p>
                  </div>
                )}

                <div className="rounded-xl border border-line bg-surface-raised p-4">
                  <p className="text-sm font-medium text-ink mb-2">Upload Email Screenshot</p>
                  <p className="text-xs text-ink-faint mb-3">
                    Take a screenshot of the email you sent and upload it here to speed up verification.
                  </p>
                  <label className="flex items-center justify-center gap-2 rounded-lg border border-dashed border-line bg-surface-sunken px-4 py-3 cursor-pointer hover:border-primary-400 hover:bg-surface-raised transition-colors">
                    <Upload className="h-4 w-4 text-ink-faint" />
                    <span className="text-sm text-ink-muted">
                      {screenshotFile ? screenshotFile.name : 'Click to upload screenshot'}
                    </span>
                    <input
                      type="file"
                      accept="image/*"
                      className="hidden"
                      onChange={(e) => {
                        const file = e.target.files?.[0];
                        if (file) setScreenshotFile(file);
                      }}
                    />
                  </label>
                </div>

                {uploadError && (
                  <div className="rounded-xl border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-600 dark:text-red-300">
                    {uploadError}
                  </div>
                )}

                {uploadSuccess && (
                  <div className="rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm text-emerald-600 dark:text-emerald-300 flex items-center gap-2">
                    <CheckCircle2 className="h-4 w-4" />
                    Screenshot uploaded successfully. We will review it shortly.
                  </div>
                )}
                {registrationDone && uploadSuccess && (
                  <div className="rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm text-emerald-600 dark:text-emerald-300 flex items-center gap-2">
                    <CheckCircle2 className="h-4 w-4" />
                    Registration complete! You can now sign in.
                  </div>
                )}
              </div>
            )}
          </CardContent>

          <CardFooter className="flex-col gap-4">
            <div className="flex w-full gap-3">
              {step > 0 && step < STEPS.length - 1 && (
                <Button variant="outline" onClick={prev} className="flex-1">
                  <ArrowLeft className="h-4 w-4" /> Back
                </Button>
              )}
              {step === 0 && (
                <Button
                  onClick={next}
                  className="flex-1"
                  disabled={!isStep0Valid}
                >
                  Continue <ArrowRight className="h-4 w-4" />
                </Button>
              )}
              {step === 1 && (
                <Button onClick={next} className="flex-1" disabled={!isStep1Valid}>
                  Continue <ArrowRight className="h-4 w-4" />
                </Button>
              )}
              {step === 2 && (
                <>
                  {registrationDone && !requiresVerificationPage ? (
                    <Link href="/login" className="flex-1">
                      <Button className="w-full" variant="secondary">
                        Sign In
                        <ArrowRight className="ml-2 h-4 w-4" />
                      </Button>
                    </Link>
                  ) : (
                    <Button onClick={handleSubmit} className="flex-1" loading={loading} disabled={registrationDone}>
                      {loading ? 'Creating account...' : verificationCode ? 'Account Created' : 'Create Account'}
                      {!loading && !verificationCode && <ArrowRight className="h-4 w-4" />}
                    </Button>
                  )}
                  {verificationCode && requiresVerificationPage && uploadSuccess && (
                    <Button onClick={() => router.push('/login')} className="flex-1" variant="secondary">
                      Complete Registration
                      <ArrowRight className="ml-2 h-4 w-4" />
                    </Button>
                  )}
                  {verificationCode && requiresVerificationPage && !uploadSuccess && (
                    <Button
                      onClick={handleUploadScreenshot}
                      className="flex-1"
                      loading={uploadingScreenshot}
                      disabled={!screenshotFile}
                    >
                      {uploadingScreenshot ? 'Uploading...' : 'Upload Screenshot'}
                      {!uploadingScreenshot && <Upload className="h-4 w-4" />}
                    </Button>
                  )}
                </>
              )}
            </div>
            <p className="text-center text-sm text-ink-muted">
              Already have an account?{' '}
              <Link href="/login" className="font-semibold text-primary-600 hover:underline">Sign in</Link>
            </p>
            <p className="text-center text-xs text-ink-faint">
              By signing up, you agree to our Terms of Service and Privacy Policy
            </p>
          </CardFooter>
        </Card>
      </div>
    </div>
  );
}
