import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Check, Server, HardDrive, ChevronDown } from 'lucide-react';
import { Card, Button } from '@/components/ui';
import { ExpandableInfo } from '@/components/pricing/ExpandableInfo';
import { gpsTiers, equipmentMonitoring } from '@/lib/pricing-data';
import { formatCurrency } from '@/lib/utils';
import type { GPSSelection, GPSTierId } from '@/types/quote';

export interface Step2GPSMonitoringProps {
  gpsSelection: GPSSelection;
  onSetGPSTier: (tierId: GPSTierId) => void;
  onSetEquipmentEnabled: (enabled: boolean) => void;
  onSetEquipmentCount: (count: number) => void;
  getGPSMonthly: () => number;
}

export function Step2GPSMonitoring({
  gpsSelection,
  onSetGPSTier,
  onSetEquipmentEnabled,
  onSetEquipmentCount,
  getGPSMonthly,
}: Step2GPSMonitoringProps) {
  const [expandedTiers, setExpandedTiers] = useState<Record<string, boolean>>({});

  const toggleTierExpanded = (tierId: string) => {
    setExpandedTiers(prev => ({ ...prev, [tierId]: !prev[tierId] }));
  };

  const calculateEquipmentPrice = () => {
    if (!gpsSelection.includeEquipment || gpsSelection.equipmentDeviceCount === 0) {
      return 0;
    }
    const additionalDevices = Math.max(0, gpsSelection.equipmentDeviceCount - equipmentMonitoring.baseDevices);
    return equipmentMonitoring.basePrice + (additionalDevices * equipmentMonitoring.additionalDevicePrice);
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
      className="space-y-6"
    >
      {/* Service Explainer */}
      <div className="space-y-2">
        <p className="text-sm sm:text-base text-gray-500 leading-relaxed">
          <strong className="text-[#333d49]">GPS (Guru Protection Suite)</strong> is our core
          managed monitoring service. We install a lightweight agent on each of your endpoints that
          runs 24/7 in the background &mdash; watching system health, disk space, CPU/memory usage,
          security status, and more.
        </p>
        <p className="text-sm text-gray-400 leading-relaxed">
          When an issue is detected, our team is automatically alerted and can often resolve problems
          remotely before you even notice. GPS also includes automated patch management to keep
          Windows and third-party apps up to date, enterprise antivirus protection, and access to
          our help desk for day-to-day questions. Higher tiers add 24/7 support, advanced endpoint
          protection, backup and disaster recovery, and dedicated account management.
        </p>
      </div>

      {/* Endpoint Count Display */}
      <div className="flex items-center justify-between bg-[#f8f9fb] rounded-xl p-4">
        <div className="flex items-center gap-3">
          <Server className="w-5 h-5 text-[#fe7400]" />
          <span className="font-medium text-[#333d49]" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
            Endpoints to Monitor
          </span>
        </div>
        <span className="text-2xl font-bold text-[#fe7400]" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
          {gpsSelection.endpointCount}
        </span>
      </div>

      {/* Tier Selection Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3 sm:gap-4">
        {gpsTiers.map((tier, index) => {
          const isSelected = gpsSelection.tierId === tier.id;
          const monthlyPrice = tier.pricePerEndpoint * gpsSelection.endpointCount;

          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={() => onSetGPSTier(tier.id)}
              >
                {/* Recommended Badge */}
                {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" }}>
                    Recommended
                  </div>
                )}

                <div className="p-5">
                  {/* Header */}
                  <div className="mb-4">
                    <h3 className="text-lg font-bold text-[#333d49]"
                        style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                      {tier.name}
                    </h3>
                    <p className="text-sm text-gray-400 mt-0.5">{tier.description}</p>
                  </div>

                  {/* Pricing */}
                  <div className="mb-5">
                    <div className="flex items-baseline gap-1">
                      <span className="text-3xl font-bold text-[#333d49]"
                            style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                        {formatCurrency(monthlyPrice)}
                      </span>
                      <span className="text-gray-400 text-sm">/mo</span>
                    </div>
                    <p className="text-xs text-gray-400 mt-1">
                      {formatCurrency(tier.pricePerEndpoint)}/endpoint/month
                    </p>
                  </div>

                  {/* Features */}
                  <ul className="space-y-2.5 mb-5">
                    {tier.features.slice(0, 4).map((feature, idx) => (
                      <li key={idx} className="flex items-start gap-2.5 text-sm">
                        <div className="w-4 h-4 rounded-full bg-[#fe7400]/10 flex items-center justify-center flex-shrink-0 mt-0.5">
                          <Check className="w-2.5 h-2.5 text-[#fe7400]" strokeWidth={3} />
                        </div>
                        <span className="text-gray-600">{feature}</span>
                      </li>
                    ))}
                    <AnimatePresence>
                      {expandedTiers[tier.id] && tier.features.slice(4).map((feature, idx) => (
                        <motion.li
                          key={`extra-${idx}`}
                          initial={{ opacity: 0, height: 0 }}
                          animate={{ opacity: 1, height: 'auto' }}
                          exit={{ opacity: 0, height: 0 }}
                          transition={{ duration: 0.2 }}
                          className="flex items-start gap-2.5 text-sm"
                        >
                          <div className="w-4 h-4 rounded-full bg-[#fe7400]/10 flex items-center justify-center flex-shrink-0 mt-0.5">
                            <Check className="w-2.5 h-2.5 text-[#fe7400]" strokeWidth={3} />
                          </div>
                          <span className="text-gray-600">{feature}</span>
                        </motion.li>
                      ))}
                    </AnimatePresence>
                    {tier.features.length > 4 && (
                      <li>
                        <button
                          type="button"
                          onClick={(e) => { e.stopPropagation(); toggleTierExpanded(tier.id); }}
                          className="flex items-center gap-1 text-xs text-[#fe7400] font-medium pl-6.5 hover:text-[#e56800] transition-colors"
                        >
                          <ChevronDown className={`w-3 h-3 transition-transform duration-200 ${expandedTiers[tier.id] ? 'rotate-180' : ''}`} />
                          {expandedTiers[tier.id]
                            ? 'Show less'
                            : `+${tier.features.length - 4} more features`
                          }
                        </button>
                      </li>
                    )}
                  </ul>

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

      {/* Equipment Monitoring Section */}
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: 0.3 }}
        className="border border-gray-200/80 rounded-xl p-5 bg-white shadow-card"
      >
        <div className="flex items-start justify-between gap-3 mb-4">
          <div className="flex items-center gap-3 min-w-0">
            <div className="w-9 h-9 rounded-lg bg-[#fe7400]/8 flex items-center justify-center flex-shrink-0">
              <HardDrive className="w-4.5 h-4.5 text-[#fe7400]" />
            </div>
            <div className="min-w-0">
              <h4 className="font-semibold text-[#333d49] text-sm sm:text-base"
                  style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                Equipment Pack Monitoring
              </h4>
              <p className="text-xs sm:text-sm text-gray-400">
                Monitor routers, switches, printers, and other network equipment
              </p>
            </div>
          </div>
          <label className="relative inline-flex items-center cursor-pointer flex-shrink-0">
            <input
              type="checkbox"
              checked={gpsSelection.includeEquipment}
              onChange={(e) => onSetEquipmentEnabled(e.target.checked)}
              className="sr-only peer"
            />
            <div className="w-11 h-6 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-5 after:w-5 after:transition-all peer-checked:bg-[#fe7400]"></div>
          </label>
        </div>

        {gpsSelection.includeEquipment && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            transition={{ duration: 0.2 }}
            className="space-y-4 pt-4 border-t border-gray-100"
          >
            <div className="flex items-center gap-4">
              <label className="text-sm text-gray-500"
                     style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                Number of devices:
              </label>
              <input
                type="number"
                min={1}
                value={gpsSelection.equipmentDeviceCount}
                onChange={(e) => onSetEquipmentCount(parseInt(e.target.value, 10) || 1)}
                className="w-24 px-3 py-2.5 rounded-xl border border-gray-200 bg-white text-[#333d49] hover:border-gray-300 focus:outline-none focus:ring-2 focus:ring-[#fe7400]/15 focus:border-[#fe7400] transition-all"
              />
            </div>
            <div className="bg-[#f8f9fb] rounded-xl p-4">
              <p className="text-sm text-gray-500">
                <span className="font-semibold text-[#333d49]">{formatCurrency(equipmentMonitoring.basePrice)}/month</span>
                {' '}for up to {equipmentMonitoring.baseDevices} devices
                {gpsSelection.equipmentDeviceCount > equipmentMonitoring.baseDevices && (
                  <span>
                    {' + '}
                    <span className="font-semibold text-[#333d49]">
                      {formatCurrency(equipmentMonitoring.additionalDevicePrice)}/device
                    </span>
                    {' for additional devices'}
                  </span>
                )}
              </p>
              <p className="text-sm font-bold text-[#fe7400] mt-2"
                 style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                Equipment total: {formatCurrency(calculateEquipmentPrice())}/month
              </p>
            </div>
          </motion.div>
        )}
      </motion.div>

      {/* Expandable Feature Info */}
      <ExpandableInfo title="What's included in GPS Monitoring?">
        <ul className="space-y-3">
          <li className="flex items-start gap-2.5">
            <div className="w-4 h-4 rounded-full bg-[#fe7400]/10 flex items-center justify-center flex-shrink-0 mt-0.5">
              <Check className="w-2.5 h-2.5 text-[#fe7400]" strokeWidth={3} />
            </div>
            <span><strong>Remote Monitoring:</strong> 24/7 monitoring of system health, performance, and security</span>
          </li>
          <li className="flex items-start gap-2.5">
            <div className="w-4 h-4 rounded-full bg-[#fe7400]/10 flex items-center justify-center flex-shrink-0 mt-0.5">
              <Check className="w-2.5 h-2.5 text-[#fe7400]" strokeWidth={3} />
            </div>
            <span><strong>Patch Management:</strong> Automated Windows and third-party application updates</span>
          </li>
          <li className="flex items-start gap-2.5">
            <div className="w-4 h-4 rounded-full bg-[#fe7400]/10 flex items-center justify-center flex-shrink-0 mt-0.5">
              <Check className="w-2.5 h-2.5 text-[#fe7400]" strokeWidth={3} />
            </div>
            <span><strong>Antivirus:</strong> Enterprise-grade protection with real-time threat detection</span>
          </li>
          <li className="flex items-start gap-2.5">
            <div className="w-4 h-4 rounded-full bg-[#fe7400]/10 flex items-center justify-center flex-shrink-0 mt-0.5">
              <Check className="w-2.5 h-2.5 text-[#fe7400]" strokeWidth={3} />
            </div>
            <span><strong>Help Desk:</strong> Access to our technical support team for issues and questions</span>
          </li>
        </ul>
      </ExpandableInfo>

      {/* Monthly Total */}
      <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">GPS Monitoring Monthly Total</span>
        <span className="text-2xl sm:text-3xl font-bold whitespace-nowrap" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
          {formatCurrency(getGPSMonthly())}
          <span className="text-xs sm:text-sm font-medium opacity-60 ml-1">/mo</span>
        </span>
      </div>
    </motion.div>
  );
}
