import { motion } from 'framer-motion';
import { Edit2, Monitor, Headphones, Phone, Globe, Mail, Printer, DollarSign, ArrowRight } from 'lucide-react';
import { Button } from '@/components/ui';
import {
  gpsTiers,
  supportPlans,
  blockTimeOptions,
  voipTiers,
  webHostingTiers,
  emailTiers,
} from '@/lib/pricing-data';
import { formatCurrency } from '@/lib/utils';
import type { QuoteData, QuoteResult } from '@/types/quote';

export interface Step6SummaryProps {
  quoteData: QuoteData;
  quoteResult: QuoteResult | null;
  onGoToStep: (step: number) => void;
  onCalculateQuote: () => QuoteResult;
}

export function Step6Summary({
  quoteData,
  quoteResult,
  onGoToStep,
  onCalculateQuote,
}: Step6SummaryProps) {
  const result = quoteResult || onCalculateQuote();

  const gpsTier = gpsTiers.find((t) => t.id === quoteData.gps.tierId);
  const supportPlan = supportPlans.find((p) => p.id === quoteData.support.planId);
  const blockTime = quoteData.support.useBlockTime && quoteData.support.blockTimeId
    ? blockTimeOptions.find((b) => b.id === quoteData.support.blockTimeId)
    : null;
  const voipTier = voipTiers.find((t) => t.id === quoteData.voip.tierId);
  const webTier = webHostingTiers.find((t) => t.id === quoteData.webHosting.tierId);
  const emailTier = emailTiers.find((t) => t.id === quoteData.email.tierId);

  const handlePrint = () => {
    // Brief delay to ensure print-only elements render
    requestAnimationFrame(() => window.print());
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
      className="space-y-6"
    >
      {/* Print-only branded header */}
      <div className="hidden print-show mb-6" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
        <div className="flex items-center justify-between pb-4 border-b-2 border-[#fe7400]">
          <div>
            <h1 className="text-2xl font-bold text-[#333d49]">Arizona Computer Guru</h1>
            <p className="text-sm text-gray-400">Managed IT Services Quote</p>
          </div>
          <div className="text-right text-sm text-gray-400">
            <p>{new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}</p>
            <p>Valid for 30 days</p>
          </div>
        </div>
      </div>

      {/* Header */}
      <div className="text-center mb-8 print-hide">
        <h2 className="text-2xl font-bold text-[#333d49] mb-2"
            style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
          Your Quote Summary
        </h2>
        <p className="text-gray-400">Review your selections before submitting</p>
      </div>

      {/* Company Info */}
      {quoteData.company.name && (
        <div className="bg-[#f8f9fb] rounded-xl p-5 mb-6 border border-gray-200/50">
          <p className="text-[11px] text-gray-400 mb-1 uppercase tracking-wider font-medium"
             style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
            Quote prepared for
          </p>
          <p className="font-bold text-[#333d49] text-lg"
             style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
            {quoteData.company.name}
          </p>
          {quoteData.company.industry && (
            <p className="text-sm text-gray-400">{quoteData.company.industry}</p>
          )}
        </div>
      )}

      {/* GPS Monitoring Section - only show if enabled */}
      {quoteData.serviceInterests.gps && (
        <SummarySection
          icon={<Monitor className="w-5 h-5" />}
          title="GPS Monitoring"
          monthlyTotal={result.gpsMonthly}
          onEdit={() => onGoToStep(1)}
        >
          <div className="space-y-2">
            <SummaryLine
              label={`${gpsTier?.name} Plan (${quoteData.gps.endpointCount} endpoints)`}
              value={formatCurrency(result.breakdown.gps.monitoring)}
            />
            {quoteData.gps.includeEquipment && quoteData.gps.equipmentDeviceCount > 0 && (
              <SummaryLine
                label={`Equipment Pack (${quoteData.gps.equipmentDeviceCount} devices)`}
                value={formatCurrency(result.breakdown.gps.equipment)}
              />
            )}
          </div>
        </SummarySection>
      )}

      {/* Support Plan Section - only show if enabled */}
      {quoteData.serviceInterests.support && (
        <SummarySection
          icon={<Headphones className="w-5 h-5" />}
          title="Support Plan"
          monthlyTotal={result.supportMonthly}
          onEdit={() => onGoToStep(2)}
        >
          <div className="space-y-2">
            {quoteData.support.planId === 'none' ? (
              <SummaryLine
                label="No Monthly Plan (pay-as-you-go)"
                value="$0"
              />
            ) : (
              <SummaryLine
                label={`${supportPlan?.name} Plan (${supportPlan?.includedHours} hrs/mo)`}
                value={formatCurrency(result.breakdown.support.plan)}
              />
            )}
            {blockTime && (
              <SummaryLine
                label={`Block Time (${blockTime.hours} hours) — one-time`}
                value={formatCurrency(result.breakdown.support.blockTime)}
              />
            )}
          </div>
        </SummarySection>
      )}

      {/* VoIP Section */}
      {quoteData.voip.enabled && (
        <SummarySection
          icon={<Phone className="w-5 h-5" />}
          title="VoIP Phone System"
          monthlyTotal={result.voipMonthly}
          onEdit={() => onGoToStep(3)}
        >
          <div className="space-y-2">
            <SummaryLine
              label={`${voipTier?.name} Plan (${quoteData.voip.userCount} users)`}
              value={formatCurrency(result.breakdown.voip.service)}
            />
            {result.breakdown.voip.hardware > 0 && (
              <SummaryLine
                label="Hardware Rental"
                value={formatCurrency(result.breakdown.voip.hardware)}
              />
            )}
          </div>
        </SummarySection>
      )}

      {/* Web Hosting Section */}
      {quoteData.webHosting.enabled && (
        <SummarySection
          icon={<Globe className="w-5 h-5" />}
          title="Web Hosting"
          monthlyTotal={result.webHostingMonthly}
          onEdit={() => onGoToStep(4)}
        >
          <SummaryLine
            label={`${webTier?.name} Plan (${webTier?.storage}, ${webTier?.sites === -1 ? 'unlimited' : webTier?.sites} sites)`}
            value={formatCurrency(result.webHostingMonthly)}
          />
        </SummarySection>
      )}

      {/* Email Section */}
      {quoteData.email.enabled && (
        <SummarySection
          icon={<Mail className="w-5 h-5" />}
          title="Email Service"
          monthlyTotal={result.emailMonthly}
          onEdit={() => onGoToStep(4)}
        >
          <SummaryLine
            label={`${emailTier?.name} (${quoteData.email.mailboxCount} mailboxes)`}
            value={formatCurrency(result.emailMonthly)}
          />
        </SummarySection>
      )}

      {/* Grand Total */}
      <motion.div
        initial={{ opacity: 0, scale: 0.98 }}
        animate={{ opacity: 1, scale: 1 }}
        transition={{ delay: 0.3 }}
        className="bg-gradient-navy text-white rounded-2xl p-6 sm:p-8 mt-8"
      >
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-4 mb-5">
          <span className="text-base sm:text-lg font-medium text-white/80">Monthly Investment</span>
          <span className="text-3xl sm:text-4xl font-bold" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
            {formatCurrency(result.monthlyTotal)}
            <span className="text-sm sm:text-base font-medium text-white/50 ml-1">/mo</span>
          </span>
        </div>

        {result.oneTimeTotal > 0 && (
          <div className="flex items-center justify-between py-4 border-t border-white/10">
            <span className="text-white/60">One-Time Costs</span>
            <span className="text-xl font-bold" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
              {formatCurrency(result.oneTimeTotal)}
            </span>
          </div>
        )}

        <div className="pt-4 border-t border-white/10">
          <div className="flex items-center justify-between text-sm text-white/50">
            <span>Annual Investment</span>
            <span className="font-medium">{formatCurrency(result.monthlyTotal * 12)}/year</span>
          </div>
        </div>
      </motion.div>

      {/* Breakdown Card */}
      <div className="bg-white rounded-xl border border-gray-200/80 shadow-card p-5 sm:p-6">
        <h4 className="font-bold text-[#333d49] mb-5 flex items-center gap-2"
            style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
          <DollarSign className="w-5 h-5 text-[#fe7400]" />
          Monthly Breakdown
        </h4>
        <div className="space-y-3">
          {quoteData.serviceInterests.gps && (
            <BreakdownRow label="GPS Monitoring" value={result.gpsMonthly} />
          )}
          {quoteData.serviceInterests.support && (
            <BreakdownRow label="Support Plan" value={result.supportMonthly} />
          )}
          {quoteData.serviceInterests.voip && quoteData.voip.enabled && (
            <BreakdownRow label="VoIP Phone System" value={result.voipMonthly} />
          )}
          {quoteData.serviceInterests.webHosting && quoteData.webHosting.enabled && (
            <BreakdownRow label="Web Hosting" value={result.webHostingMonthly} />
          )}
          {quoteData.serviceInterests.email && quoteData.email.enabled && (
            <BreakdownRow label="Email Service" value={result.emailMonthly} />
          )}
          <div className="pt-4 mt-1 border-t-2 border-[#fe7400]/20 flex justify-between items-center">
            <span className="font-bold text-[#333d49] text-lg"
                  style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
              Total
            </span>
            <span className="font-bold text-[#fe7400] text-xl"
                  style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
              {formatCurrency(result.monthlyTotal)}/mo
            </span>
          </div>
        </div>
      </div>

      {/* Print Button */}
      <div className="flex justify-center pt-2 print-hide">
        <Button
          variant="ghost"
          onClick={handlePrint}
          className="flex items-center gap-2 text-gray-400"
        >
          <Printer className="w-4 h-4" />
          Print Quote
        </Button>
      </div>

      {/* Notes Section */}
      <div className="text-center text-xs text-gray-400 pt-2 space-y-1">
        <p>This is an estimate. Final pricing may vary based on specific requirements.</p>
        <p>Prices are subject to change. Quote valid for 30 days.</p>
      </div>

      {/* Print-only footer */}
      <div className="hidden print-show mt-8 pt-4 border-t border-gray-200 text-center text-xs text-gray-400">
        <p>Arizona Computer Guru &middot; azcomputerguru.com &middot; (480) 400-3798</p>
      </div>
    </motion.div>
  );
}

// Helper Components

interface SummarySectionProps {
  icon: React.ReactNode;
  title: string;
  monthlyTotal: number;
  onEdit: () => void;
  children: React.ReactNode;
}

function SummarySection({ icon, title, monthlyTotal, onEdit, children }: SummarySectionProps) {
  return (
    <motion.div
      initial={{ opacity: 0, x: -10 }}
      animate={{ opacity: 1, x: 0 }}
      className="border border-gray-200/80 rounded-xl overflow-hidden bg-white shadow-card print-section"
    >
      <div className="bg-[#f8f9fb] px-4 sm:px-5 py-3 sm:py-3.5 flex items-center justify-between gap-2">
        <div className="flex items-center gap-2 sm:gap-3 min-w-0">
          <span className="text-[#fe7400] flex-shrink-0">{icon}</span>
          <span className="font-bold text-[#333d49] text-sm sm:text-base truncate"
                style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
            {title}
          </span>
        </div>
        <div className="flex items-center gap-2 sm:gap-4 flex-shrink-0">
          <span className="font-bold text-[#333d49] text-sm sm:text-base whitespace-nowrap"
                style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
            {formatCurrency(monthlyTotal)}
            <span className="text-xs font-medium text-gray-400 ml-0.5">/mo</span>
          </span>
          <button
            type="button"
            onClick={onEdit}
            className="flex items-center gap-1 sm:gap-1.5 text-xs sm:text-sm text-[#fe7400] hover:text-[#e56800] font-semibold transition-colors print-hide"
            style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}
          >
            <Edit2 className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
            Edit
          </button>
        </div>
      </div>
      <div className="p-5">{children}</div>
    </motion.div>
  );
}

interface SummaryLineProps {
  label: string;
  value: string;
}

function SummaryLine({ label, value }: SummaryLineProps) {
  return (
    <div className="flex justify-between items-center text-sm">
      <span className="text-gray-500 flex items-center gap-2">
        <ArrowRight className="w-3 h-3 text-gray-300" />
        {label}
      </span>
      <span className="font-semibold text-[#333d49]"
            style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
        {value}
      </span>
    </div>
  );
}

interface BreakdownRowProps {
  label: string;
  value: number;
}

function BreakdownRow({ label, value }: BreakdownRowProps) {
  return (
    <div className="flex justify-between items-center py-1">
      <span className="text-gray-500">{label}</span>
      <span className="font-semibold text-[#333d49]"
            style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
        {formatCurrency(value)}
      </span>
    </div>
  );
}
