'use client';

import { motion } from 'framer-motion';
import {
  CheckCircle2, Cpu, BarChart3, Star, Crown, Shield,
  Users, FolderKanban, Zap, Lock, Clock, Building2,
  FileCode2,
} from 'lucide-react';
import { useSession } from '../lib/session-context';
import { getPlanCapabilities } from '../lib/plan-access';

interface Props {
  onNavigate: (section: string) => void;
}

const PLANS = [
  {
    id: 'starter',
    name: 'Starter',
    color: 'text-sky-400',
    bg: 'bg-sky-500/10',
    border: 'border-sky-500/20',
    activeBorder: 'border-sky-400/60',
    icon: Star,
    bestFor: 'Small teams modernizing selected services',
    users: 'Up to 5',
    projects: 'Up to 5 conversions / year',
    sla: '48h email support',
    unique: [
      'Fast onboarding with guided migration workflow',
      'Token visibility dashboard for usage tracking',
      'Audit-ready activity history for each project',
    ],
    highlights: [
      'Web dashboard',
      'All modern languages (30+)',
      'E2E encryption + zero retention',
      'Token consumption dashboard',
      'GDPR compliance + DPA',
      'Complete audit log',
      'Quarterly newsletter',
    ],
  },
  {
    id: 'professional',
    name: 'Professional',
    color: 'text-purple-400',
    bg: 'bg-purple-500/10',
    border: 'border-purple-500/20',
    activeBorder: 'border-purple-400/60',
    icon: Crown,
    bestFor: 'Growing migration programs across mixed stacks',
    users: 'Up to 25',
    projects: 'Up to 15 conversions / year',
    sla: '24h email support',
    unique: [
      'Legacy + modern language coverage in one workspace',
      'SSO-ready access for larger internal teams',
      'Quality reports for stakeholder sign-off',
    ],
    highlights: [
      'Everything in Starter',
      'Legacy & mainframe languages',
      'SSO (SAML 2.0 / Okta / Azure AD)',
      'Conversion quality report',
      'SOC 2 Type II / ISO 27001',
      'EU AI Act compliance',
      'Quarterly webinar included',
    ],
  },
  {
    id: 'enterprise',
    name: 'Enterprise',
    color: 'text-amber-400',
    bg: 'bg-amber-500/10',
    border: 'border-amber-500/20',
    activeBorder: 'border-amber-400/60',
    icon: Shield,
    bestFor: 'Large enterprises with strict controls and scale',
    users: 'Unlimited',
    projects: 'Up to 40 conversions / year',
    sla: '8h support + Slack/Teams',
    unique: [
      'Enterprise control plane with granular RBAC',
      'On-prem / air-gapped deployment support',
      'Dedicated account leadership and architecture guidance',
    ],
    highlights: [
      'Everything in Professional',
      'Granular RBAC',
      'On-premise / air-gapped deploy',
      'Dedicated account manager',
      'Technical consulting available',
      'Custom volume token pricing',
      'Multi-year discount available',
    ],
  },
] as const;

const COMPLEXITY_GROUPS = [
  {
    name: 'Group 1 — Modern',
    mult: '1.0×',
    color: 'text-green-400',
    bg: 'bg-green-500/10',
    border: 'border-green-500/20',
    languages: 'Python, TypeScript, Java, C#, Go, Rust, Kotlin, Swift, PHP, Ruby, C++, Dart',
    example: 'Python → Go',
  },
  {
    name: 'Group 2 — Legacy & Mainframe',
    mult: '2.5×',
    color: 'text-amber-400',
    bg: 'bg-amber-500/10',
    border: 'border-amber-500/20',
    languages: 'COBOL, Visual Basic 6, Pascal/Delphi, PowerBuilder, RPG/400, FORTRAN, PL/I, Natural/ADABAS, ABAP, REXX, PHP 4/5 legacy',
    example: 'COBOL → Java',
  },
  {
    name: 'Group 3 — Mainframe+',
    mult: '3.0×',
    color: 'text-red-400',
    bg: 'bg-red-500/10',
    border: 'border-red-500/20',
    languages: 'Assembler z/OS, CICS/BMS, CL/400, JCL, MUMPS/M',
    example: 'Assembler → C++',
  },
];

const FEATURE_MATRIX = [
  { feature: 'Web dashboard',                     starter: true,  professional: true,  enterprise: true  },
  { feature: 'E2E encryption + Zero retention',   starter: true,  professional: true,  enterprise: true  },
  { feature: 'Complete audit log',                starter: true,  professional: true,  enterprise: true  },
  { feature: 'Token consumption dashboard',       starter: true,  professional: true,  enterprise: true  },
  { feature: 'GDPR compliance + DPA',             starter: true,  professional: true,  enterprise: true  },
  { feature: 'Modern languages (30+)',            starter: true,  professional: true,  enterprise: true  },
  { feature: 'Support SLA',                       starter: '48h', professional: '24h', enterprise: '8h'  },
  { feature: 'Users included',                    starter: '5',   professional: '25',  enterprise: '∞'   },
  { feature: 'Conversions / year',                 starter: '5',   professional: '15',  enterprise: '40'  },
  { feature: 'SSO (SAML 2.0 / Okta / Azure AD)', starter: false, professional: true,  enterprise: true  },
  { feature: 'Legacy & mainframe languages',      starter: false, professional: true,  enterprise: true  },
  { feature: 'Conversion quality report',         starter: false, professional: true,  enterprise: true  },
  { feature: 'SOC 2 Type II / ISO 27001',         starter: false, professional: true,  enterprise: true  },
  { feature: 'EU AI Act compliance',              starter: false, professional: true,  enterprise: true  },
  { feature: 'Quarterly webinar',                 starter: false, professional: true,  enterprise: true  },
  { feature: 'Granular RBAC',                     starter: false, professional: false, enterprise: true  },
  { feature: 'On-premise / air-gapped deploy',    starter: false, professional: false, enterprise: true  },
  { feature: 'Dedicated Slack/Teams channel',     starter: false, professional: false, enterprise: true  },
  { feature: 'Dedicated account manager',         starter: false, professional: false, enterprise: true  },
  { feature: 'Technical consulting',              starter: false, professional: false, enterprise: true  },
];

function Cell({ value }: { value: boolean | string }) {
  if (typeof value === 'string') {
    return <span className="text-xs font-semibold text-foreground">{value}</span>;
  }
  return value
    ? <CheckCircle2 className="w-4 h-4 text-green-400 mx-auto" />
    : <span className="text-muted/40 text-sm">—</span>;
}

export default function PilotProgram({ onNavigate }: Props) {
  const { user: sessionUser } = useSession();
  const isAdmin = sessionUser?.role === 'admin';
  const capabilities = getPlanCapabilities(sessionUser?.tier);
  const currentTier = isAdmin ? 'enterprise' : capabilities.tier;

  const currentPlan = PLANS.find(p => p.id === currentTier) ?? PLANS[0];
  const CurrentIcon = currentPlan.icon;

  return (
    <div className="space-y-8">

      {/* ── Header ── */}
      <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }}
        className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-foreground">Plans & Features</h2>
          <p className="text-sm text-muted mt-1">Compare package strengths, capabilities, and what each tier unlocks</p>
        </div>
        <span className={`px-3 py-1.5 rounded-full text-xs font-semibold capitalize border ${currentPlan.bg} ${currentPlan.color} ${currentPlan.border}`}>
          {isAdmin ? 'Admin · Full Access' : `${currentPlan.name} Plan`}
        </span>
      </motion.div>

      {/* ── Current Plan Summary ── */}
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.05 }}
        className={`glass rounded-2xl p-6 border ${currentPlan.activeBorder}`}>
        <div className="flex items-start gap-4 mb-6">
          <div className={`w-12 h-12 rounded-xl flex items-center justify-center ${currentPlan.bg} border ${currentPlan.border}`}>
            <CurrentIcon className={`w-6 h-6 ${currentPlan.color}`} />
          </div>
          <div className="flex-1">
            <div className="flex items-center gap-2 mb-1">
              <h3 className="text-lg font-bold text-foreground">{currentPlan.name}</h3>
              <span className={`text-[10px] px-2 py-0.5 rounded-full font-semibold ${currentPlan.bg} ${currentPlan.color} border ${currentPlan.border}`}>
                Your plan
              </span>
            </div>
            <p className="text-sm text-muted">{currentPlan.bestFor}</p>
          </div>
        </div>

        <div className="grid grid-cols-3 gap-4 mb-6">
          {[
            { icon: Users,         label: 'Users',          value: currentPlan.users },
            { icon: FolderKanban,  label: 'Conversions / Year', value: currentPlan.projects },
            { icon: Clock,         label: 'Support SLA',    value: currentPlan.sla },
          ].map(stat => (
            <div key={stat.label} className="glass-light rounded-xl p-4">
              <div className="flex items-center gap-2 mb-2">
                <stat.icon className={`w-4 h-4 ${currentPlan.color}`} />
                <p className="text-[10px] text-muted uppercase tracking-wider font-medium">{stat.label}</p>
              </div>
              <p className="text-sm font-bold text-foreground">{stat.value}</p>
            </div>
          ))}
        </div>

        <div className="mb-6">
          <p className="text-xs font-semibold text-muted uppercase tracking-wider mb-3">What makes this package unique</p>
          <div className="grid sm:grid-cols-3 gap-3">
            {currentPlan.unique.map(item => (
              <div key={item} className="glass-light rounded-xl px-3 py-2.5 text-xs text-foreground">
                {item}
              </div>
            ))}
          </div>
        </div>

        <div>
          <p className="text-xs font-semibold text-muted uppercase tracking-wider mb-3">What's included</p>
          <div className="grid sm:grid-cols-2 gap-x-6 gap-y-2">
            {currentPlan.highlights.map(h => (
              <div key={h} className="flex items-center gap-2 text-sm text-muted">
                <CheckCircle2 className="w-3.5 h-3.5 text-green-400 shrink-0" />
                <span>{h}</span>
              </div>
            ))}
          </div>
        </div>
      </motion.div>

      {/* ── Plan Comparison ── */}
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}>
        <h3 className="text-sm font-bold text-foreground mb-4 flex items-center gap-2">
          <Building2 className="w-4 h-4 text-accent-light" /> All Plans
        </h3>
        <div className="grid grid-cols-3 gap-4">
          {PLANS.map(plan => {
            const Icon = plan.icon;
            const isActive = plan.id === currentTier;
            return (
              <div key={plan.id}
                className={`glass rounded-2xl p-5 border transition-all ${isActive ? plan.activeBorder : 'border-border'}`}>
                <div className={`w-10 h-10 rounded-xl flex items-center justify-center mb-4 ${plan.bg} border ${plan.border}`}>
                  <Icon className={`w-5 h-5 ${plan.color}`} />
                </div>

                <div className="flex items-start justify-between mb-1">
                  <p className="text-sm font-bold text-foreground">{plan.name}</p>
                  {isActive && (
                    <span className={`text-[9px] px-1.5 py-0.5 rounded-full font-semibold ${plan.bg} ${plan.color}`}>current</span>
                  )}
                </div>
                <p className="text-[11px] text-muted mb-4">{plan.bestFor}</p>

                <div className="space-y-2 mb-4">
                  {[
                    { icon: Users,        label: plan.users + ' users' },
                    { icon: FolderKanban, label: plan.projects },
                    { icon: Clock,        label: plan.sla },
                  ].map(item => (
                    <div key={item.label} className="flex items-center gap-2 text-xs text-muted">
                      <item.icon className={`w-3.5 h-3.5 ${plan.color} shrink-0`} />
                      <span>{item.label}</span>
                    </div>
                  ))}
                </div>

                <div className="mb-4 rounded-lg bg-surface/50 border border-border/60 p-3">
                  <p className="text-[10px] text-muted uppercase tracking-wider mb-2">Standout strengths</p>
                  <div className="space-y-1.5">
                    {plan.unique.map(point => (
                      <div key={point} className="flex items-start gap-1.5 text-[11px] text-foreground">
                        <Zap className={`w-3 h-3 mt-0.5 shrink-0 ${plan.color}`} />
                        <span>{point}</span>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="border-t border-border/50 pt-3 space-y-1.5">
                  {plan.highlights.map(h => (
                    <div key={h} className="flex items-start gap-1.5 text-[11px] text-muted">
                      <CheckCircle2 className="w-3 h-3 text-green-400 mt-0.5 shrink-0" />
                      <span>{h}</span>
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </motion.div>

      {/* ── Complexity Multipliers ── */}
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}
        className="glass rounded-2xl p-6">
        <h3 className="text-sm font-bold text-foreground mb-1 flex items-center gap-2">
          <Cpu className="w-4 h-4 text-accent-light" /> Conversion Complexity Multipliers
        </h3>
        <p className="text-[11px] text-muted mb-4">Token cost is multiplied based on language complexity. All languages are accessible on Professional and Enterprise plans.</p>
        <div className="space-y-3">
          {COMPLEXITY_GROUPS.map(g => {
            const isLocked = g.name !== 'Group 1 — Modern' && currentTier === 'starter';
            return (
              <div key={g.name} className={`rounded-xl p-4 border relative overflow-hidden ${g.bg} ${g.border} ${isLocked ? 'opacity-60' : ''}`}>
                {isLocked && (
                  <div className="absolute top-3 right-3">
                    <Lock className="w-3.5 h-3.5 text-muted" />
                  </div>
                )}
                <div className="flex items-center justify-between mb-2">
                  <div>
                    <span className={`text-xs font-semibold ${g.color}`}>{g.name}</span>
                    {isLocked && <span className="ml-2 text-[9px] text-muted">Professional+ required</span>}
                  </div>
                  <div className="text-right">
                    <p className={`text-lg font-bold tabular-nums ${g.color}`}>{g.mult}</p>
                  </div>
                </div>
                <p className="text-[11px] text-muted leading-relaxed">{g.languages}</p>
                <div className="flex items-center gap-1.5 mt-2 text-[10px] text-muted/60">
                  <FileCode2 className="w-3 h-3" />
                  <span>Example: {g.example}</span>
                </div>
              </div>
            );
          })}
        </div>
      </motion.div>

      {/* ── Feature Matrix ── */}
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.25 }}
        className="glass rounded-2xl p-6">
        <h3 className="text-sm font-bold text-foreground mb-4 flex items-center gap-2">
          <BarChart3 className="w-4 h-4 text-accent-light" /> Full Feature Comparison
        </h3>
        <div className="overflow-x-auto">
          <table className="w-full text-xs">
            <thead>
              <tr className="border-b border-border">
                <th className="text-left text-muted font-medium py-2 pr-4 w-1/2">Feature</th>
                {PLANS.map(plan => {
                  const isActive = plan.id === currentTier;
                  return (
                    <th key={plan.id} className={`text-center py-2 px-3 font-semibold ${isActive ? plan.color : 'text-muted'}`}>
                      {plan.name}
                      {isActive && (
                        <span className={`ml-1 text-[9px] px-1.5 py-0.5 rounded-full ${plan.bg} ${plan.color}`}>current</span>
                      )}
                    </th>
                  );
                })}
              </tr>
            </thead>
            <tbody>
              {FEATURE_MATRIX.map((row, i) => (
                <tr key={row.feature} className={`border-b border-border/50 ${i % 2 === 0 ? '' : 'bg-surface/30'}`}>
                  <td className="py-2.5 pr-4 text-muted">{row.feature}</td>
                  <td className="py-2.5 px-3 text-center"><Cell value={row.starter} /></td>
                  <td className="py-2.5 px-3 text-center"><Cell value={row.professional} /></td>
                  <td className="py-2.5 px-3 text-center"><Cell value={row.enterprise} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </motion.div>

    </div>
  );
}
