'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useAuth } from '@/lib/hooks/useAuth';
import {
  MessageSquare, Mail, Users, Zap, CheckCircle2, ArrowUpRight,
  Settings, Sparkles, Rocket
} from 'lucide-react';

interface SetupStatus {
  smsConfigured: boolean;
  emailConfigured: boolean;
  contactsImported: boolean;
  campaignsSetup: boolean;
}

export default function SetupPage() {
  const { user } = useAuth();
  const [progress, setProgress] = useState<SetupStatus>({
    smsConfigured: false,
    emailConfigured: false,
    contactsImported: false,
    campaignsSetup: false,
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('/api/v1/onboarding/status')
      .then(res => res.json())
      .then(data => {
        if (data.setupStatus) {
          setProgress(data.setupStatus);
        }
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const steps = [
    {
      key: 'smsConfigured',
      label: 'Configure SMS',
      description: 'Set up two-way texting with A2P registration to communicate with your contacts via SMS.',
      done: progress.smsConfigured,
      href: '/settings/sms',
      icon: MessageSquare,
      color: 'purple'
    },
    {
      key: 'emailConfigured',
      label: 'Set up Email',
      description: 'Connect your email account and configure domain authentication for better deliverability.',
      done: progress.emailConfigured,
      href: '/settings/email',
      icon: Mail,
      color: 'orange'
    },
    {
      key: 'contactsImported',
      label: 'Import Contacts',
      description: 'Bring in your existing database of contacts to start managing relationships.',
      done: progress.contactsImported,
      href: '/contacts',
      icon: Users,
      color: 'blue'
    },
    {
      key: 'campaignsSetup',
      label: 'Create Campaigns',
      description: 'Set up automated follow-up campaigns to nurture your leads and stay top of mind.',
      done: progress.campaignsSetup,
      href: '/automations',
      icon: Zap,
      color: 'emerald'
    },
  ];

  const completedCount = steps.filter(s => s.done).length;
  const progressPercent = (completedCount / steps.length) * 100;
  const isComplete = progressPercent === 100;

  const colorClasses: Record<string, { bg: string; icon: string; border: string }> = {
    purple: { bg: 'bg-purple-100', icon: 'text-purple-600', border: 'border-purple-200' },
    orange: { bg: 'bg-orange-100', icon: 'text-orange-600', border: 'border-orange-200' },
    blue: { bg: 'bg-blue-100', icon: 'text-blue-600', border: 'border-blue-200' },
    emerald: { bg: 'bg-emerald-100', icon: 'text-emerald-600', border: 'border-emerald-200' },
  };

  return (
    <div className="space-y-8 pb-8 max-w-4xl mx-auto">
      {/* Header */}
      <div className="clay-card-subtle p-6 border border-border/50">
        <div className="flex items-center gap-4">
          <div className={`w-14 h-14 rounded-2xl flex items-center justify-center ${
            isComplete ? 'bg-emerald-100' : 'bg-primary/10'
          }`}>
            {isComplete ? (
              <CheckCircle2 className="w-7 h-7 text-emerald-600" />
            ) : (
              <Settings className="w-7 h-7 text-primary" />
            )}
          </div>
          <div>
            <h1 className="text-3xl font-bold text-foreground">
              {isComplete ? 'Setup Complete!' : 'Setup Your Account'}
            </h1>
            <p className="text-slate-500 text-lg mt-1">
              {isComplete
                ? `Great job${user?.firstName ? `, ${user.firstName}` : ''}! You're ready to make the most of CRESync.`
                : `Complete these steps to unlock all features${user?.firstName ? `, ${user.firstName}` : ''}.`}
            </p>
          </div>
        </div>
      </div>

      {/* Progress Overview */}
      <div className="clay-card p-6 border border-border/50">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-6">
          <div className="flex items-center gap-3">
            <div className={`w-11 h-11 rounded-xl flex items-center justify-center ${
              isComplete ? 'bg-emerald-100' : 'bg-primary/10'
            }`}>
              {isComplete ? (
                <Sparkles className="w-5 h-5 text-emerald-600" />
              ) : (
                <Rocket className="w-5 h-5 text-primary" />
              )}
            </div>
            <div>
              <h2 className="text-xl font-bold text-foreground">Progress Overview</h2>
              <p className="text-sm text-slate-500">
                {completedCount} of {steps.length} steps completed
              </p>
            </div>
          </div>
          <div className={`flex items-center gap-2 px-4 py-2 rounded-full font-bold ${
            isComplete
              ? 'bg-emerald-100 text-emerald-700'
              : 'bg-primary/10 text-primary'
          }`}>
            <span className="text-2xl">{Math.round(progressPercent)}%</span>
            <span className="text-sm font-medium">complete</span>
          </div>
        </div>

        {/* Progress Bar */}
        <div className="p-4 rounded-xl bg-slate-50 border border-slate-200">
          <div className="h-4 bg-slate-200 rounded-full overflow-hidden">
            <div
              className={`h-full rounded-full transition-all duration-700 ease-out ${
                isComplete
                  ? 'bg-gradient-to-r from-emerald-500 to-emerald-400'
                  : 'bg-gradient-to-r from-primary via-indigo-500 to-violet-500'
              }`}
              style={{ width: `${progressPercent}%` }}
            />
          </div>
          <div className="flex justify-between mt-3">
            {steps.map((step, index) => (
              <div
                key={step.key}
                className={`flex items-center gap-1.5 ${
                  step.done ? 'text-emerald-600' : 'text-slate-400'
                }`}
              >
                {step.done ? (
                  <CheckCircle2 className="w-4 h-4" />
                ) : (
                  <span className="w-4 h-4 rounded-full border-2 border-current" />
                )}
                <span className="text-xs font-medium hidden sm:inline">{step.label.split(' ')[0]}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Setup Steps */}
      <div className="space-y-4">
        <div className="clay-card-subtle p-5 border border-border/50">
          <h2 className="text-xl font-bold text-foreground">Setup Steps</h2>
          <p className="text-sm text-slate-500 mt-1">Complete each step to get the most out of CRESync</p>
        </div>

        {loading ? (
          <div className="space-y-4">
            {[1, 2, 3, 4].map((i) => (
              <div key={i} className="clay-card p-6 border border-border/50">
                <div className="flex items-start gap-4">
                  <div className="w-14 h-14 rounded-xl bg-slate-200 animate-pulse" />
                  <div className="flex-1 space-y-2">
                    <div className="h-5 w-1/3 bg-slate-200 rounded animate-pulse" />
                    <div className="h-4 w-2/3 bg-slate-200 rounded animate-pulse" />
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="space-y-4">
            {steps.map((step, index) => {
              const StepIcon = step.icon;
              const colors = colorClasses[step.color];

              return (
                <div
                  key={step.key}
                  className={`clay-card p-6 border transition-all ${
                    step.done
                      ? 'border-emerald-200 bg-emerald-50/50'
                      : 'border-border/50 hover:border-primary/30'
                  }`}
                >
                  <div className="flex flex-col sm:flex-row sm:items-center gap-4">
                    {/* Step Number & Icon */}
                    <div className="flex items-center gap-3">
                      <div className={`w-10 h-10 rounded-full flex items-center justify-center font-bold text-lg ${
                        step.done
                          ? 'bg-emerald-500 text-white'
                          : 'bg-slate-100 text-slate-500 border-2 border-slate-300'
                      }`}>
                        {step.done ? (
                          <CheckCircle2 className="w-5 h-5" />
                        ) : (
                          index + 1
                        )}
                      </div>
                      <div className={`w-14 h-14 rounded-xl flex items-center justify-center ${
                        step.done ? 'bg-emerald-100' : colors.bg
                      }`}>
                        <StepIcon className={`w-7 h-7 ${step.done ? 'text-emerald-600' : colors.icon}`} />
                      </div>
                    </div>

                    {/* Content */}
                    <div className="flex-1 min-w-0">
                      <h3 className={`text-lg font-bold ${step.done ? 'text-emerald-700' : 'text-foreground'}`}>
                        {step.label}
                      </h3>
                      <p className="text-slate-500 mt-1">{step.description}</p>
                    </div>

                    {/* Action */}
                    <div className="flex-shrink-0">
                      {step.done ? (
                        <span className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg bg-emerald-100 text-emerald-700 font-semibold text-sm">
                          <CheckCircle2 className="w-4 h-4" />
                          Completed
                        </span>
                      ) : (
                        <Link
                          href={step.href}
                          className="inline-flex items-center gap-2 px-5 py-2.5 rounded-lg bg-primary text-white font-semibold text-sm hover:bg-primary/90 transition-colors"
                        >
                          Get Started
                          <ArrowUpRight className="w-4 h-4" />
                        </Link>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Completion Message */}
      {isComplete && (
        <div className="clay-card p-8 border border-emerald-200 bg-gradient-to-br from-emerald-50 to-teal-50 text-center">
          <div className="w-20 h-20 mx-auto mb-4 rounded-full bg-emerald-100 flex items-center justify-center">
            <Sparkles className="w-10 h-10 text-emerald-600" />
          </div>
          <h2 className="text-2xl font-bold text-emerald-800 mb-2">You're All Set!</h2>
          <p className="text-emerald-700 mb-6 max-w-md mx-auto">
            Your account is fully configured. Start managing your contacts, running campaigns, and closing more deals.
          </p>
          <Link
            href="/dashboard"
            className="inline-flex items-center gap-2 px-6 py-3 rounded-xl bg-emerald-600 text-white font-semibold hover:bg-emerald-700 transition-colors"
          >
            Go to Dashboard
            <ArrowUpRight className="w-5 h-5" />
          </Link>
        </div>
      )}
    </div>
  );
}
