import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../auth/store/AuthContext';
import { DocumentPreview } from '../../agreements/components/DocumentPreview';
import { SignatureCapture } from '../../../components/organisms/SignatureCapture';
import type { SignaturePayload, User } from '../../../types';
import { apiClient } from '../../../lib/api-client';
import {
  CheckCircle2,
  ChevronRight,
  FileSignature,
  Landmark,
  Building2,
  Globe,
  Loader2,
  ShieldAlert,
  ShieldX,
  LogOut,
  Sparkles,
  ArrowRight
} from 'lucide-react';

export const OnboardingWizard: React.FC = () => {
  const { user, updateUserLocal, logout } = useAuth();
  const navigate = useNavigate();

  // Determine current active step based on onboarding status and signature state
  const getStepIndex = (currentUser: User | null): number => {
    if (!currentUser) return 0;
    if (currentUser.onboardingStatus === 'NOT_STARTED') return 0;
    if (currentUser.onboardingStatus === 'FORM_COMPLETED') return 1;
    if (currentUser.onboardingStatus === 'NDA_SIGNED') return 2;
    if (currentUser.onboardingStatus === 'PENDING_APPROVAL' || currentUser.onboardingStatus === 'REJECTED') return 3;
    if (currentUser.onboardingStatus === 'APPROVED') {
      if (!currentUser.ndaSignature) return 1;
      if (!currentUser.msaSignature) return 2;
      return 4; // Completed
    }
    return 0;
  };

  const [step, setStep] = useState<number>(() => getStepIndex(user));

  // Step 0: Profile Form State
  const [companyName, setCompanyName] = useState(user?.companyName || '');
  const [website, setWebsite] = useState(user?.website || '');
  const [sector, setSector] = useState(user?.sector || 'Technology');
  const [companySize, setCompanySize] = useState(user?.companySize || '1-10');
  const [errors, setErrors] = useState<{ [key: string]: string }>({});
  const [saving, setSaving] = useState(false);

  // Signature state
  const [signingDoc, setSigningDoc] = useState<'NDA' | 'MSA' | null>(null);
  const [redirecting, setRedirecting] = useState(false);

  // Sync step state when user status updates
  useEffect(() => {
    if (user) {
      const targetStep = getStepIndex(user);
      setStep(targetStep);

      // Initialize form fields if they were empty
      if (user.companyName && !companyName) setCompanyName(user.companyName);
      if (user.website && !website) setWebsite(user.website);
      if (user.sector && sector === 'Technology') setSector(user.sector);
      if (user.companySize && companySize === '1-10') setCompanySize(user.companySize);

      // Auto-redirect if onboarding is fully complete
      if (targetStep === 4 && !redirecting) {
        setRedirecting(true);
        const timer = setTimeout(() => {
          navigate('/client');
        }, 2000);
        return () => clearTimeout(timer);
      }
    }
  }, [user, navigate, redirecting]);

  // Real-time polling for admin approval/rejection status
  useEffect(() => {
    if (!user || user.onboardingStatus !== 'PENDING_APPROVAL') return;

    const interval = setInterval(async () => {
      try {
        const response = await apiClient.get<User>('/auth/session');
        if (response.data.onboardingStatus !== 'PENDING_APPROVAL') {
          updateUserLocal(response.data);
        }
      } catch (err) {
        console.error('Error polling onboarding status:', err);
      }
    }, 3000); // Poll every 3 seconds

    return () => clearInterval(interval);
  }, [user, updateUserLocal]);

  const validateForm = () => {
    const newErrors: { [key: string]: string } = {};
    if (!companyName.trim()) newErrors.companyName = 'Company name is required';
    if (!website.trim()) {
      newErrors.website = 'Website is required';
    } else if (!/^https?:\/\/[^\s$.?#].[^\s]*$/i.test(website)) {
      newErrors.website = 'Enter a valid URL (e.g., https://example.com)';
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleProfileSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validateForm()) return;

    setSaving(true);
    try {
      const response = await apiClient.post<User>('/client/onboarding', {
        companyName,
        website,
        sector,
        companySize,
      });
      updateUserLocal(response.data);
    } catch (err) {
      console.error(err);
    } finally {
      setSaving(false);
    }
  };

  const handleSaveSignature = async (payload: SignaturePayload) => {
    if (!signingDoc) return;

    setSaving(true);
    try {
      const endpoint = signingDoc === 'NDA' ? '/client/nda' : '/client/msa';
      const response = await apiClient.post<User>(endpoint, payload);
      updateUserLocal(response.data);
      setSigningDoc(null);
    } catch (err) {
      console.error(err);
    } finally {
      setSaving(false);
    }
  };

  // Steps breadcrumb styling (stepper has 4 primary steps)
  const stepsList = [
    { title: 'Profile', icon: Building2 },
    { title: 'NDA Agreement', icon: FileSignature },
    { title: 'MSA Agreement', icon: Landmark },
    { title: 'Admin Review', icon: ShieldAlert }
  ];

  return (
    <div className="mx-auto max-w-4xl p-4 md:p-8">
      {/* Step Indicator */}
      <div className="mb-8 rounded-xl border border-ink-100 bg-white p-4 shadow-sm md:p-6">
        <div className="flex items-center justify-between">
          {stepsList.map((s, idx) => {
            const Icon = s.icon;
            // The step is index-based.
            const isCompleted = step > idx;
            const isActive = step === idx;

            return (
              <React.Fragment key={s.title}>
                <div className="flex flex-col items-center gap-1.5 md:flex-row md:gap-3">
                  <div
                    className={`flex h-10 w-10 items-center justify-center rounded-full transition-all duration-300 ${
                      isCompleted
                        ? 'bg-success text-white'
                        : isActive
                        ? 'bg-primary-400 text-ink-800 ring-4 ring-primary-100'
                        : 'bg-ink-100 text-ink-600'
                    }`}
                  >
                    {isCompleted ? (
                      <CheckCircle2 className="h-5 w-5" />
                    ) : (
                      <Icon className="h-5 w-5" />
                    )}
                  </div>
                  <div className="text-center md:text-left">
                    <p className={`text-[10px] font-bold uppercase tracking-wider ${isActive ? 'text-primary-700' : 'text-ink-600'}`}>
                      Step {idx + 1}
                    </p>
                    <p className={`text-xs font-semibold ${isActive ? 'text-ink-800' : 'text-ink-600'}`}>
                      {s.title}
                    </p>
                  </div>
                </div>
                {idx < stepsList.length - 1 && (
                  <div className="hidden h-[2px] flex-1 bg-ink-100 md:block mx-4" />
                )}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      {/* Forms & Screens */}
      {step === 0 && (
        <div className="rounded-xl border border-ink-100 bg-white p-6 shadow-premium transition-premium">
          <div className="mb-6">
            <h2 className="text-xl font-bold text-ink-800">Business Profile</h2>
            <p className="text-sm text-ink-600">Please provide your business and legal details to start the partnership onboarding.</p>
          </div>

          <form onSubmit={handleProfileSubmit} className="space-y-5">
            <div className="grid gap-5 md:grid-cols-2">
              <div>
                <label className="block text-xs font-semibold text-ink-700 mb-1.5 flex items-center gap-1">
                  <Building2 className="h-3.5 w-3.5 text-ink-600" />
                  Legal Company Name
                </label>
                <input
                  type="text"
                  value={companyName}
                  onChange={(e) => setCompanyName(e.target.value)}
                  className={`w-full rounded-lg border px-3.5 py-2 text-sm focus:border-primary-500 focus:outline-none transition-colors ${
                    errors.companyName ? 'border-danger bg-danger/5' : 'border-ink-200'
                  }`}
                  placeholder="e.g. Acme Tech Ltd."
                />
                {errors.companyName && (
                  <p className="mt-1 text-xs text-danger font-medium">{errors.companyName}</p>
                )}
              </div>

              <div>
                <label className="block text-xs font-semibold text-ink-700 mb-1.5 flex items-center gap-1">
                  <Globe className="h-3.5 w-3.5 text-ink-600" />
                  Corporate Website
                </label>
                <input
                  type="text"
                  value={website}
                  onChange={(e) => setWebsite(e.target.value)}
                  className={`w-full rounded-lg border px-3.5 py-2 text-sm focus:border-primary-500 focus:outline-none transition-colors ${
                    errors.website ? 'border-danger bg-danger/5' : 'border-ink-200'
                  }`}
                  placeholder="e.g. https://acme.com"
                />
                {errors.website && (
                  <p className="mt-1 text-xs text-danger font-medium">{errors.website}</p>
                )}
              </div>
            </div>

            <div className="grid gap-5 md:grid-cols-2">
              <div>
                <label className="block text-xs font-semibold text-ink-700 mb-1.5">Industry Sector</label>
                <select
                  value={sector}
                  onChange={(e) => setSector(e.target.value)}
                  className="w-full rounded-lg border border-ink-200 bg-white px-3.5 py-2 text-sm focus:border-primary-500 focus:outline-none"
                >
                  <option value="Technology">Technology & Software</option>
                  <option value="Automotive">Automotive & Robotics</option>
                  <option value="Telecommunications">Telecommunications</option>
                  <option value="Defense">Aerospace & Defense</option>
                  <option value="Semiconductors">Semiconductors & HW</option>
                  <option value="Other">Other Industries</option>
                </select>
              </div>

              <div>
                <label className="block text-xs font-semibold text-ink-700 mb-1.5">Company Size</label>
                <select
                  value={companySize}
                  onChange={(e) => setCompanySize(e.target.value)}
                  className="w-full rounded-lg border border-ink-200 bg-white px-3.5 py-2 text-sm focus:border-primary-500 focus:outline-none"
                >
                  <option value="1-10">1 - 10 employees</option>
                  <option value="10-50">10 - 50 employees</option>
                  <option value="50-250">50 - 250 employees</option>
                  <option value="250-1000">250 - 1000 employees</option>
                  <option value="1000+">1000+ employees</option>
                </select>
              </div>
            </div>

            <div className="flex justify-end pt-4 border-t border-ink-100">
              <button
                type="submit"
                disabled={saving}
                className="flex items-center gap-2 rounded-lg bg-primary-400 px-6 py-2.5 text-sm font-semibold text-ink-800 hover:bg-primary-300 disabled:opacity-50 disabled:cursor-not-allowed transition-premium shadow-premium"
              >
                {saving ? 'Saving...' : 'Save & Continue'}
                <ChevronRight className="h-4 w-4" />
              </button>
            </div>
          </form>
        </div>
      )}

      {step === 1 && (
        <div className="space-y-6">
          <div className="rounded-xl border border-ink-100 bg-white p-6 shadow-premium animate-premium">
            <h2 className="text-xl font-bold text-ink-800">Mutual Non-Disclosure Agreement (NDA)</h2>
            <p className="text-sm text-ink-600 mb-4">Please review and electronically sign our mutual NDA to request access to restricted silicon design files and proprietary source repositories.</p>

            <DocumentPreview
              title="Mutual Non-Disclosure Agreement (NDA)"
              documentType="NDA"
              companyName={companyName}
              signatureDataUrl={user?.ndaSignature?.dataUrl}
              signatureDate={user?.ndaSignature?.date}
            />

            {!user?.ndaSignature && !signingDoc && (
              <div className="mt-6 flex justify-end">
                <button
                  type="button"
                  onClick={() => setSigningDoc('NDA')}
                  className="flex items-center gap-2 rounded-lg bg-primary-400 px-6 py-2.5 text-sm font-semibold text-ink-800 hover:bg-primary-300 transition-premium shadow-premium cursor-pointer"
                >
                  <FileSignature className="h-4 w-4" />
                  Sign NDA Agreement
                </button>
              </div>
            )}

            {user?.ndaSignature && (
              <div className="mt-6 flex justify-between items-center bg-success/5 border border-success/20 p-4 rounded-lg animate-premium">
                <div className="flex items-center gap-2 text-success">
                  <CheckCircle2 className="h-5 w-5" />
                  <span className="text-sm font-semibold">NDA Agreement Signed Successfully</span>
                </div>
                <button
                  type="button"
                  onClick={() => setStep(2)}
                  className="flex items-center gap-1 text-sm font-bold text-primary-800 hover:underline cursor-pointer"
                >
                  Proceed to MSA
                  <ChevronRight className="h-4 w-4" />
                </button>
              </div>
            )}
          </div>

          {signingDoc === 'NDA' && (
            <div className="mt-4 animate-premium">
              <h3 className="text-base font-bold text-ink-800 mb-3 flex items-center gap-2">
                <FileSignature className="h-5 w-5 text-primary-600" />
                Sign Document: NDA
              </h3>
              <SignatureCapture
                onSave={handleSaveSignature}
                onCancel={() => setSigningDoc(null)}
              />
            </div>
          )}
        </div>
      )}

      {step === 2 && (
        <div className="space-y-6">
          <div className="rounded-xl border border-ink-100 bg-white p-6 shadow-premium animate-premium">
            <div className="mb-4 flex items-center justify-between">
              <div>
                <h2 className="text-xl font-bold text-ink-800">Master Services Agreement (MSA)</h2>
                <p className="text-sm text-ink-600">Please review and sign the Master Services Agreement specifying licensing structures.</p>
              </div>
              <button
                onClick={() => setStep(1)}
                className="text-xs text-ink-600 hover:underline cursor-pointer"
              >
                Back to NDA
              </button>
            </div>

            <DocumentPreview
              title="Master Services Agreement (MSA)"
              documentType="MSA"
              companyName={companyName}
              signatureDataUrl={user?.msaSignature?.dataUrl}
              signatureDate={user?.msaSignature?.date}
            />

            {!user?.msaSignature && !signingDoc && (
              <div className="mt-6 flex justify-end">
                <button
                  type="button"
                  onClick={() => setSigningDoc('MSA')}
                  className="flex items-center gap-2 rounded-lg bg-primary-400 px-6 py-2.5 text-sm font-semibold text-ink-800 hover:bg-primary-300 transition-premium shadow-premium cursor-pointer"
                >
                  <FileSignature className="h-4 w-4" />
                  Sign MSA Agreement
                </button>
              </div>
            )}

            {user?.msaSignature && (
              <div className="mt-6 flex justify-between items-center bg-success/5 border border-success/20 p-4 rounded-lg animate-premium">
                <div className="flex items-center gap-2 text-success">
                  <CheckCircle2 className="h-5 w-5" />
                  <span className="text-sm font-semibold">MSA Agreement Signed Successfully</span>
                </div>
              </div>
            )}
          </div>

          {signingDoc === 'MSA' && (
            <div className="mt-4 animate-premium">
              <h3 className="text-base font-bold text-ink-800 mb-3 flex items-center gap-2">
                <FileSignature className="h-5 w-5 text-primary-600" />
                Sign Document: MSA
              </h3>
              <SignatureCapture
                onSave={handleSaveSignature}
                onCancel={() => setSigningDoc(null)}
              />
            </div>
          )}
        </div>
      )}

      {step === 3 && user?.onboardingStatus === 'PENDING_APPROVAL' && (
        <div className="rounded-xl border border-ink-100 bg-white p-8 shadow-premium text-center space-y-6 animate-premium">
          <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-warning/10 border border-warning/20">
            <Loader2 className="h-8 w-8 text-warning animate-spin" />
          </div>
          <div>
            <h2 className="text-2xl font-bold text-ink-800 mb-2">Partnership Review Pending</h2>
            <p className="mx-auto max-w-md text-sm text-ink-600">
              Thank you! Your company details have been submitted. Your registration request is currently awaiting administrator review.
            </p>
          </div>

          {/* Details inspection */}
          <div className="mx-auto max-w-md border border-ink-100 rounded-xl bg-ink-50/50 p-4 text-left space-y-3">
            <h3 className="text-xs font-bold uppercase tracking-wider text-ink-600 border-b border-ink-100 pb-1.5 flex items-center gap-1.5">
              <Building2 className="w-3.5 h-3.5 text-ink-500" /> Submitted Profile Details
            </h3>
            <div className="grid grid-cols-2 gap-3 text-xs">
              <div>
                <p className="font-semibold text-ink-500">Company Name</p>
                <p className="font-bold text-ink-800 mt-0.5">{user.companyName}</p>
              </div>
              <div>
                <p className="font-semibold text-ink-500">Corporate Website</p>
                <a href={user.website} target="_blank" rel="noreferrer" className="font-bold text-primary-700 hover:underline flex items-center gap-0.5 mt-0.5">
                  <Globe className="w-3 h-3" /> Visit Link
                </a>
              </div>
              <div>
                <p className="font-semibold text-ink-500">Industry Sector</p>
                <p className="font-bold text-ink-800 mt-0.5">{user.sector}</p>
              </div>
              <div>
                <p className="font-semibold text-ink-500">Company Size</p>
                <p className="font-bold text-ink-800 mt-0.5">{user.companySize} employees</p>
              </div>
            </div>
          </div>

          <div className="border-t border-ink-100 pt-6 flex flex-col items-center gap-3">
            <p className="text-xs text-ink-500 max-w-lg">
              Once an administrator reviews your application and signed agreements, you will be granted full access to the portal dashboard.
            </p>
            <button
              onClick={logout}
              className="flex items-center gap-1.5 text-sm font-semibold text-danger hover:underline px-4 py-2 border border-danger/10 bg-danger/5 rounded-lg transition-colors mt-2 cursor-pointer"
            >
              <LogOut className="h-4 w-4" />
              Sign Out
            </button>
          </div>
        </div>
      )}

      {step === 3 && user?.onboardingStatus === 'REJECTED' && (
        <div className="rounded-xl border border-danger/20 bg-white p-8 shadow-premium text-center space-y-6 animate-premium">
          <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-danger/10 border border-danger/20">
            <ShieldX className="h-8 w-8 text-danger animate-pulse" />
          </div>
          <div>
            <h2 className="text-2xl font-bold text-danger mb-2">Registration Declined</h2>
            <p className="mx-auto max-w-md text-sm text-ink-600">
              We regret to inform you that your request for partnership access to the Tech4Biz Developer Portal was not approved by our compliance team.
            </p>
          </div>

          <div className="mx-auto max-w-md border border-danger/10 rounded-xl bg-danger/5 p-4 text-left">
            <p className="text-xs text-danger font-semibold leading-relaxed">
              Compliance Notice: Your business profile does not satisfy our current regional/regulatory developer guidelines. If you believe this is an error or wish to submit additional verification, please contact us.
            </p>
          </div>

          <div className="border-t border-ink-100 pt-6 flex flex-col items-center gap-3">
            <button
              onClick={logout}
              className="flex items-center gap-1.5 text-sm font-semibold text-danger hover:underline px-6 py-2.5 border border-danger/30 bg-danger/5 rounded-lg transition-colors cursor-pointer"
            >
              <LogOut className="h-4 w-4" />
              Return to Login
            </button>
          </div>
        </div>
      )}

      {step === 4 && (
        <div className="rounded-xl border border-ink-100 bg-white p-8 shadow-premium text-center space-y-6 transition-premium">
          <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-success/10 border border-success/20">
            <Sparkles className="h-8 w-8 text-success animate-pulse" />
          </div>
          <div>
            <h2 className="text-2xl font-bold text-ink-800 mb-2">Onboarding Completed!</h2>
            <p className="mx-auto max-w-md text-sm text-ink-600">
              Welcome to Tech4Biz! Your profile is approved and both agreements (NDA & MSA) are signed and filed.
            </p>
          </div>

          <div className="flex flex-col items-center gap-3">
            <span className="text-xs text-ink-500">Redirecting to your dashboard...</span>
            <button
              onClick={() => navigate('/client')}
              className="flex items-center gap-2 rounded-lg bg-primary-400 px-6 py-2.5 text-sm font-semibold text-ink-800 hover:bg-primary-300 transition-premium shadow-premium"
            >
              Enter Portal <ArrowRight className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}
    </div>
  );
};
