import { motion, AnimatePresence } from 'framer-motion';
import { Check, Globe, Mail, Cloud, Server } from 'lucide-react';
import { Card, Button, Input } from '@/components/ui';
import { ExpandableInfo } from '@/components/pricing/ExpandableInfo';
import { webHostingTiers, emailTiers } from '@/lib/pricing-data';
import { formatCurrency } from '@/lib/utils';
import type {
  WebHostingSelection,
  WebHostingTierId,
  EmailSelection,
  EmailTierId,
  EmailProvider,
} from '@/types/quote';

export interface Step5WebEmailProps {
  webHostingSelection: WebHostingSelection;
  emailSelection: EmailSelection;
  onSetWebHostingEnabled: (enabled: boolean) => void;
  onSetWebHostingTier: (tierId: WebHostingTierId) => void;
  onSetEmailEnabled: (enabled: boolean) => void;
  onSetEmailProvider: (provider: EmailProvider) => void;
  onSetEmailTier: (tierId: EmailTierId) => void;
  onSetMailboxCount: (count: number) => void;
  getWebHostingMonthly: () => number;
  getEmailMonthly: () => number;
}

export function Step5WebEmail({
  webHostingSelection,
  emailSelection,
  onSetWebHostingEnabled,
  onSetWebHostingTier,
  onSetEmailEnabled,
  onSetEmailProvider,
  onSetEmailTier,
  onSetMailboxCount,
  getWebHostingMonthly,
  getEmailMonthly,
}: Step5WebEmailProps) {
  const whmTiers = emailTiers.filter((t) => t.provider === 'whm');
  const m365Tiers = emailTiers.filter((t) => t.provider === 'm365');

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
      className="space-y-8"
    >
      {/* Service Explainer */}
      <div className="space-y-2">
        <p className="text-sm sm:text-base text-gray-500 leading-relaxed">
          <strong className="text-[#333d49]">Web hosting and email</strong> are often managed
          separately from IT, but bundling them with your MSP means one point of contact for
          everything. We handle the technical details &mdash; SSL certificates, backups, security
          updates, DNS, and spam filtering &mdash; so you don't have to.
        </p>
        <p className="text-sm text-gray-400 leading-relaxed">
          For email, choose between our budget-friendly self-hosted option (great for basic
          email needs) or Microsoft 365, which includes Outlook, Teams, OneDrive, and the
          full Office suite. Both options include professional yourname@yourcompany.com addresses
          and spam protection.
        </p>
      </div>

      {/* Web Hosting Section */}
      <div className="space-y-4">
        <div className="bg-[#f8f9fb] rounded-xl p-4 sm:p-5">
          <div className="flex items-center justify-between gap-3">
            <div className="flex items-center gap-3 min-w-0">
              <div className="w-9 h-9 sm:w-10 sm:h-10 rounded-xl bg-[#fe7400]/8 flex items-center justify-center flex-shrink-0">
                <Globe className="w-4 h-4 sm:w-5 sm:h-5 text-[#fe7400]" />
              </div>
              <div className="min-w-0">
                <h3 className="font-bold text-[#333d49] text-sm sm:text-base"
                    style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                  Web Hosting
                </h3>
                <p className="text-xs sm:text-sm text-gray-400">
                  Managed WordPress hosting with SSL and backups
                </p>
              </div>
            </div>
            <label className="relative inline-flex items-center cursor-pointer flex-shrink-0">
              <input
                type="checkbox"
                checked={webHostingSelection.enabled}
                onChange={(e) => onSetWebHostingEnabled(e.target.checked)}
                className="sr-only peer"
              />
              <div className="w-14 h-7 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-[#fe7400]/10 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-6 after:w-6 after:transition-all peer-checked:bg-[#fe7400]"></div>
              <span className="ml-3 text-sm font-semibold text-gray-500"
                    style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                {webHostingSelection.enabled ? 'Yes' : 'No'}
              </span>
            </label>
          </div>
        </div>

        <AnimatePresence>
          {webHostingSelection.enabled && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              transition={{ duration: 0.3 }}
            >
              <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3 sm:gap-4">
                {webHostingTiers.map((tier, index) => {
                  const isSelected = webHostingSelection.tierId === tier.id;

                  return (
                    <motion.div
                      key={tier.id}
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: index * 0.1 }}
                      whileHover={{ y: -3 }}
                    >
                      <Card
                        variant={isSelected ? 'highlighted' : 'default'}
                        padding="none"
                        className={`relative overflow-hidden cursor-pointer h-full ${
                          tier.recommended && !isSelected ? 'ring-2 ring-[#fe7400]/30' : ''
                        }`}
                        onClick={() => onSetWebHostingTier(tier.id)}
                      >
                        {tier.recommended && (
                          <div className="bg-gradient-accent text-white text-[11px] font-bold px-3 py-1.5 text-center uppercase tracking-wider"
                               style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                            Popular
                          </div>
                        )}

                        <div className="p-4">
                          <h3 className="text-base font-bold text-[#333d49]"
                              style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                            {tier.name}
                          </h3>
                          <p className="text-xs text-gray-400 mb-3">{tier.description}</p>

                          <div className="mb-3">
                            <span className="text-2xl font-bold text-[#333d49]"
                                  style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                              {formatCurrency(tier.monthlyPrice)}
                            </span>
                            <span className="text-gray-400 text-sm">/mo</span>
                          </div>

                          <div className="flex gap-3 mb-3 text-xs text-gray-400 font-medium">
                            <span>{tier.storage}</span>
                            <span className="text-gray-300">|</span>
                            <span>{tier.sites === -1 ? 'Unlimited' : tier.sites} site{tier.sites !== 1 && 's'}</span>
                          </div>

                          <ul className="space-y-1.5 mb-4">
                            {tier.features.slice(0, 3).map((feature, idx) => (
                              <li key={idx} className="flex items-start gap-2 text-xs">
                                <div className="w-3.5 h-3.5 rounded-full bg-[#fe7400]/10 flex items-center justify-center flex-shrink-0 mt-0.5">
                                  <Check className="w-2 h-2 text-[#fe7400]" strokeWidth={3} />
                                </div>
                                <span className="text-gray-500">{feature}</span>
                              </li>
                            ))}
                          </ul>

                          <Button
                            variant={isSelected ? 'primary' : 'outline'}
                            className="w-full"
                            size="sm"
                          >
                            {isSelected ? 'Selected' : 'Select'}
                          </Button>
                        </div>
                      </Card>
                    </motion.div>
                  );
                })}
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      {/* Divider */}
      <div className="border-t border-gray-100" />

      {/* Email Section */}
      <div className="space-y-4">
        <div className="bg-[#f8f9fb] rounded-xl p-4 sm:p-5">
          <div className="flex items-center justify-between gap-3">
            <div className="flex items-center gap-3 min-w-0">
              <div className="w-9 h-9 sm:w-10 sm:h-10 rounded-xl bg-[#fe7400]/8 flex items-center justify-center flex-shrink-0">
                <Mail className="w-4 h-4 sm:w-5 sm:h-5 text-[#fe7400]" />
              </div>
              <div className="min-w-0">
                <h3 className="font-bold text-[#333d49] text-sm sm:text-base"
                    style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                  Email Service
                </h3>
                <p className="text-xs sm:text-sm text-gray-400">
                  Professional business email hosting
                </p>
              </div>
            </div>
            <label className="relative inline-flex items-center cursor-pointer flex-shrink-0">
              <input
                type="checkbox"
                checked={emailSelection.enabled}
                onChange={(e) => onSetEmailEnabled(e.target.checked)}
                className="sr-only peer"
              />
              <div className="w-14 h-7 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-[#fe7400]/10 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-6 after:w-6 after:transition-all peer-checked:bg-[#fe7400]"></div>
              <span className="ml-3 text-sm font-semibold text-gray-500"
                    style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                {emailSelection.enabled ? 'Yes' : 'No'}
              </span>
            </label>
          </div>
        </div>

        <AnimatePresence>
          {emailSelection.enabled && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              transition={{ duration: 0.3 }}
              className="space-y-4"
            >
              {/* Mailbox Count */}
              <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4 p-4 border border-gray-200/80 rounded-xl bg-white shadow-card">
                <label className="text-sm font-medium text-[#333d49]"
                       style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                  Number of mailboxes:
                </label>
                <Input
                  type="number"
                  min={1}
                  value={emailSelection.mailboxCount}
                  onChange={(e) => onSetMailboxCount(parseInt(e.target.value, 10) || 1)}
                  className="w-full sm:w-24"
                />
              </div>

              {/* Provider Selection */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div
                  onClick={() => onSetEmailProvider('whm')}
                  className={`p-5 rounded-xl border-2 cursor-pointer transition-all duration-200 ${
                    emailSelection.provider === 'whm'
                      ? 'border-[#fe7400] bg-[#fe7400]/5 shadow-sm'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                >
                  <div className="flex items-center gap-3 mb-2">
                    <Server className="w-5 h-5 text-[#fe7400]" />
                    <h4 className="font-bold text-[#333d49]"
                        style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                      Self-Hosted (WHM)
                    </h4>
                  </div>
                  <p className="text-sm text-gray-400">
                    Budget-friendly email hosting on our servers
                  </p>
                </div>

                <div
                  onClick={() => onSetEmailProvider('m365')}
                  className={`p-5 rounded-xl border-2 cursor-pointer transition-all duration-200 ${
                    emailSelection.provider === 'm365'
                      ? 'border-[#fe7400] bg-[#fe7400]/5 shadow-sm'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                >
                  <div className="flex items-center gap-3 mb-2">
                    <Cloud className="w-5 h-5 text-[#fe7400]" />
                    <h4 className="font-bold text-[#333d49]"
                        style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                      Microsoft 365
                    </h4>
                    <span className="text-[11px] bg-gradient-accent text-white px-2 py-0.5 rounded-md font-bold uppercase tracking-wider"
                          style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                      Recommended
                    </span>
                  </div>
                  <p className="text-sm text-gray-400">
                    Full Microsoft suite with Teams, OneDrive, and Office apps
                  </p>
                </div>
              </div>

              {/* Tier Selection based on Provider */}
              <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3 sm:gap-4">
                {(emailSelection.provider === 'whm' ? whmTiers : m365Tiers).map((tier, index) => {
                  const isSelected = emailSelection.tierId === tier.id;
                  const monthlyPrice = tier.pricePerMailbox * emailSelection.mailboxCount;

                  return (
                    <motion.div
                      key={tier.id}
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: index * 0.1 }}
                      whileHover={{ y: -3 }}
                    >
                      <Card
                        variant={isSelected ? 'highlighted' : 'default'}
                        padding="none"
                        className={`relative overflow-hidden cursor-pointer h-full ${
                          tier.recommended && !isSelected ? 'ring-2 ring-[#fe7400]/30' : ''
                        }`}
                        onClick={() => onSetEmailTier(tier.id)}
                      >
                        {tier.recommended && (
                          <div className="bg-gradient-accent text-white text-[11px] font-bold px-3 py-1.5 text-center uppercase tracking-wider"
                               style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                            Popular
                          </div>
                        )}

                        <div className="p-4">
                          <h3 className="text-base font-bold text-[#333d49]"
                              style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                            {tier.name}
                          </h3>
                          <p className="text-xs text-gray-400 mb-2">{tier.storage}</p>

                          <div className="mb-3">
                            <span className="text-xl font-bold text-[#333d49]"
                                  style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                              {formatCurrency(monthlyPrice)}
                            </span>
                            <span className="text-gray-400 text-xs">/mo</span>
                            <p className="text-xs text-gray-400">
                              {formatCurrency(tier.pricePerMailbox)}/mailbox
                            </p>
                          </div>

                          <ul className="space-y-1.5 mb-3">
                            {tier.features.slice(0, 3).map((feature, idx) => (
                              <li key={idx} className="flex items-start gap-2 text-xs">
                                <div className="w-3.5 h-3.5 rounded-full bg-[#fe7400]/10 flex items-center justify-center flex-shrink-0 mt-0.5">
                                  <Check className="w-2 h-2 text-[#fe7400]" strokeWidth={3} />
                                </div>
                                <span className="text-gray-500">{feature}</span>
                              </li>
                            ))}
                          </ul>

                          <Button
                            variant={isSelected ? 'primary' : 'outline'}
                            className="w-full"
                            size="sm"
                          >
                            {isSelected ? 'Selected' : 'Select'}
                          </Button>
                        </div>
                      </Card>
                    </motion.div>
                  );
                })}
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      {/* Info */}
      <ExpandableInfo title="WHM vs Microsoft 365 - Which should I choose?">
        <div className="space-y-4">
          <div>
            <h5 className="font-semibold text-[#333d49]"
                style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
              Self-Hosted (WHM)
            </h5>
            <p className="text-sm text-gray-500 mt-1">
              Best for budget-conscious businesses that just need reliable email.
              Includes webmail access and standard email features.
            </p>
          </div>
          <div>
            <h5 className="font-semibold text-[#333d49]"
                style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
              Microsoft 365
            </h5>
            <p className="text-sm text-gray-500 mt-1">
              Best for businesses that need collaboration tools. Includes Outlook,
              Teams for video calls, OneDrive cloud storage, and the full Office
              suite (Word, Excel, PowerPoint).
            </p>
          </div>
        </div>
      </ExpandableInfo>

      {/* Totals */}
      <div className="space-y-3">
        {webHostingSelection.enabled && (
          <div className="bg-[#f8f9fb] rounded-xl p-4 flex items-center justify-between border border-gray-200/80">
            <span className="text-gray-500 font-medium">Web Hosting</span>
            <span className="text-xl font-bold text-[#333d49]"
                  style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
              {formatCurrency(getWebHostingMonthly())}
              <span className="text-sm font-medium text-gray-400 ml-1">/mo</span>
            </span>
          </div>
        )}

        {emailSelection.enabled && (
          <div className="bg-[#f8f9fb] rounded-xl p-4 flex items-center justify-between border border-gray-200/80">
            <span className="text-gray-500 font-medium">Email Service</span>
            <span className="text-xl font-bold text-[#333d49]"
                  style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
              {formatCurrency(getEmailMonthly())}
              <span className="text-sm font-medium text-gray-400 ml-1">/mo</span>
            </span>
          </div>
        )}

        {(webHostingSelection.enabled || emailSelection.enabled) && (
          <div className="bg-gradient-dark text-white rounded-xl p-4 sm:p-5 flex items-center justify-between gap-3">
            <span className="text-sm sm:text-base font-medium opacity-90">Web & Email Total</span>
            <span className="text-2xl sm:text-3xl font-bold whitespace-nowrap" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
              {formatCurrency(getWebHostingMonthly() + getEmailMonthly())}
              <span className="text-xs sm:text-sm font-medium opacity-60 ml-1">/mo</span>
            </span>
          </div>
        )}
      </div>
    </motion.div>
  );
}
