
'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Home,
  Zap,
  Layers,
  Hammer,
  ChevronRight,
  ChevronLeft,
  MapPin,
  Mail,
  Phone,
  MessageCircle,
  Send,
  Check,
  DollarSign,
  Ruler,
  Palette,
  Info,
} from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Slider } from '@/components/ui/slider';
import { toast } from 'sonner';
import { GoogleMapsSearch } from './google-maps-search';
import { QuoteSummaryBox } from './quote-summary-box';

// Project types with visual icons
const PROJECT_TYPES = [
  {
    id: 'roofing',
    name: 'Roofing',
    icon: Home,
    description: 'New roof installation or replacement',
    color: 'from-emerald-500 to-teal-600',
  },
  {
    id: 'solar',
    name: 'Solar Panels',
    icon: Zap,
    description: 'Solar energy solutions',
    color: 'from-amber-500 to-orange-600',
  },
  {
    id: 'paving',
    name: 'Paving',
    icon: Layers,
    description: 'Driveways and pathways',
    color: 'from-slate-500 to-gray-600',
  },
  {
    id: 'renovation',
    name: 'Renovation',
    icon: Hammer,
    description: 'General home improvements',
    color: 'from-blue-500 to-indigo-600',
  },
];

// Roofing materials (prices removed - visible only to CRM)
const ROOFING_MATERIALS = [
  { id: 'corrugated', name: 'Corrugated Iron' },
  { id: 'chromadek', name: 'Chromadek' },
  { id: 'klip_lock', name: 'Klip-Lok / IBR' },
  { id: 'concrete_tiles', name: 'Concrete Tiles' },
  { id: 'clay_tiles', name: 'Clay Tiles' },
  { id: 'slate', name: 'Slate / Shingles' },
];

// Solar options (prices removed - visible only to CRM)
const SOLAR_OPTIONS = [
  { id: 'grid_tied', name: 'Grid-Tied System' },
  { id: 'off_grid', name: 'Off-Grid System' },
  { id: 'hybrid', name: 'Hybrid System' },
  { id: 'battery_backup', name: 'Battery Backup Only' },
];

// Paving materials (prices removed - visible only to CRM)
const PAVING_MATERIALS = [
  { id: 'brick', name: 'Brick Paving' },
  { id: 'cobble', name: 'Cobble Paving' },
  { id: 'flagstone', name: 'Flagstone' },
  { id: 'interlock', name: 'Interlock Paving' },
];

// Budget ranges (removed - quote will be calculated by CRM)
// Customers no longer need to provide budget estimates

// Contact methods
const CONTACT_METHODS = [
  {
    id: 'whatsapp',
    name: 'WhatsApp',
    icon: MessageCircle,
    color: 'from-green-500 to-emerald-600',
    description: 'Quick messaging',
  },
  {
    id: 'phone',
    name: 'Phone Call',
    icon: Phone,
    color: 'from-blue-500 to-cyan-600',
    description: 'Direct contact',
  },
  {
    id: 'email',
    name: 'Email',
    icon: Mail,
    color: 'from-purple-500 to-pink-600',
    description: 'Detailed response',
  },
];

interface WizardData {
  projectType: string;
  material: string;
  location: {
    address: string;
    lat?: number;
    lng?: number;
  };
  contactMethod: string;
  contactInfo: {
    name: string;
    phone: string;
    email: string;
  };
  additionalNotes: string;
}

export function GuidedQuoteWizard() {
  const [currentStep, setCurrentStep] = useState(1);
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  const [wizardData, setWizardData] = useState<WizardData>({
    projectType: '',
    material: '',
    location: {
      address: '',
    },
    contactMethod: '',
    contactInfo: {
      name: '',
      phone: '',
      email: '',
    },
    additionalNotes: '',
  });

  const totalSteps = 4; // Reduced from 5 (removed budget step)

  // Get materials based on project type
  const getMaterialsForProject = () => {
    switch (wizardData.projectType) {
      case 'roofing':
        return ROOFING_MATERIALS;
      case 'solar':
        return SOLAR_OPTIONS;
      case 'paving':
        return PAVING_MATERIALS;
      default:
        return [];
    }
  };

  // Validation for each step
  const canProceed = () => {
    switch (currentStep) {
      case 1:
        return wizardData.projectType !== '';
      case 2:
        return wizardData.material !== '' || wizardData.projectType === 'renovation';
      case 3:
        return wizardData.location.address !== '';
      case 4:
        return (
          wizardData.contactMethod !== '' &&
          wizardData.contactInfo.name !== '' &&
          (wizardData.contactInfo.phone !== '' || wizardData.contactInfo.email !== '')
        );
      default:
        return false;
    }
  };

  const handleNext = () => {
    if (canProceed() && currentStep < totalSteps) {
      setCurrentStep(currentStep + 1);
    }
  };

  const handleBack = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  const handleSubmit = async () => {
    setIsSubmitting(true);
    try {
      // Prepare submission data
      const submissionData = {
        projectType: wizardData.projectType,
        material: wizardData.material,
        location: wizardData.location,
        contactMethod: wizardData.contactMethod,
        contactInfo: wizardData.contactInfo,
        additionalNotes: wizardData.additionalNotes,
      };

      const response = await fetch('/api/quote-wizard', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(submissionData),
      });

      if (!response.ok) {
        throw new Error('Failed to submit quote request');
      }

      toast.success('Quote request submitted! We\'ll contact you soon.');
      
      // Redirect based on contact method
      if (wizardData.contactMethod === 'whatsapp' && wizardData.contactInfo.phone) {
        const message = encodeURIComponent(
          `Hi! I'd like a quote for ${wizardData.projectType}. Project: ${wizardData.material}, Location: ${wizardData.location.address}`
        );
        window.open(`https://wa.me/${wizardData.contactInfo.phone.replace(/\D/g, '')}?text=${message}`, '_blank');
      }
      
      // Reset wizard
      setTimeout(() => {
        window.location.href = '/';
      }, 2000);
      
    } catch (error) {
      console.error('Error submitting quote:', error);
      toast.error('Failed to submit quote request. Please try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 via-teal-900 to-emerald-900 py-8 px-4">
      <div className="max-w-4xl mx-auto">
        {/* Progress Bar */}
        <div className="mb-8">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium text-white">
              Step {currentStep} of {totalSteps}
            </span>
            <span className="text-sm text-emerald-300">
              {Math.round((currentStep / totalSteps) * 100)}% Complete
            </span>
          </div>
          <div className="w-full bg-slate-700 rounded-full h-2">
            <motion.div
              className="bg-gradient-to-r from-emerald-500 to-teal-400 h-2 rounded-full"
              initial={{ width: 0 }}
              animate={{ width: `${(currentStep / totalSteps) * 100}%` }}
              transition={{ duration: 0.3 }}
            />
          </div>
        </div>

        {/* Step Content */}
        <AnimatePresence mode="wait">
          <motion.div
            key={currentStep}
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: -20 }}
            transition={{ duration: 0.3 }}
          >
            <Card className="bg-white/95 backdrop-blur border-none shadow-2xl">
              <CardHeader>
                <CardTitle className="text-2xl md:text-3xl text-slate-900">
                  {currentStep === 1 && 'What type of project do you need?'}
                  {currentStep === 2 && 'Select your preferred material or style'}
                  {currentStep === 3 && 'Where is your property located?'}
                  {currentStep === 4 && 'How should we contact you?'}
                </CardTitle>
                <CardDescription className="text-slate-600">
                  {currentStep === 1 && 'Choose the service you need help with'}
                  {currentStep === 2 && 'We\'ll recommend trusted contractors for your choice'}
                  {currentStep === 3 && 'We\'ll find contractors in your area'}
                  {currentStep === 4 && 'We\'ll reach out to discuss your project'}
                </CardDescription>
              </CardHeader>

              <CardContent className="space-y-6">
                {/* Step 1: Project Type */}
                {currentStep === 1 && (
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {PROJECT_TYPES.map((project) => {
                      const Icon = project.icon;
                      return (
                        <motion.button
                          key={project.id}
                          whileHover={{ scale: 1.02 }}
                          whileTap={{ scale: 0.98 }}
                          onClick={() => {
                            setWizardData({ ...wizardData, projectType: project.id, material: '' });
                          }}
                          className={`relative p-6 rounded-xl border-2 transition-all text-left ${
                            wizardData.projectType === project.id
                              ? 'border-emerald-500 bg-emerald-50'
                              : 'border-slate-200 bg-white hover:border-emerald-300'
                          }`}
                        >
                          <div className={`absolute top-0 left-0 w-full h-1 bg-gradient-to-r ${project.color} rounded-t-xl`} />
                          <Icon
                            className={`w-12 h-12 mb-3 ${
                              wizardData.projectType === project.id ? 'text-emerald-600' : 'text-slate-400'
                            }`}
                          />
                          <h3 className="text-lg font-semibold text-slate-900 mb-1">{project.name}</h3>
                          <p className="text-sm text-slate-600">{project.description}</p>
                          {wizardData.projectType === project.id && (
                            <Check className="absolute top-4 right-4 w-6 h-6 text-emerald-600" />
                          )}
                        </motion.button>
                      );
                    })}
                  </div>
                )}

                {/* Step 2: Material Selection */}
                {currentStep === 2 && (
                  <div className="space-y-4">
                    {wizardData.projectType === 'renovation' ? (
                      <div className="text-center py-8">
                        <Info className="w-16 h-16 text-emerald-500 mx-auto mb-4" />
                        <p className="text-lg text-slate-700">
                          We'll discuss specific renovation details when we contact you.
                        </p>
                        <Button
                          onClick={handleNext}
                          className="mt-4 bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-700 hover:to-teal-700"
                        >
                          Continue
                        </Button>
                      </div>
                    ) : (
                      <div className="grid grid-cols-1 gap-3">
                        {getMaterialsForProject().map((material) => (
                          <motion.button
                            key={material.id}
                            whileHover={{ scale: 1.01 }}
                            whileTap={{ scale: 0.99 }}
                            onClick={() => {
                              setWizardData({ ...wizardData, material: material.id });
                            }}
                            className={`p-4 rounded-lg border-2 transition-all flex items-center justify-between ${
                              wizardData.material === material.id
                                ? 'border-emerald-500 bg-emerald-50'
                                : 'border-slate-200 bg-white hover:border-emerald-300'
                            }`}
                          >
                            <div className="text-left">
                              <h4 className="font-semibold text-slate-900">{material.name}</h4>
                            </div>
                            {wizardData.material === material.id && (
                              <Check className="w-6 h-6 text-emerald-600" />
                            )}
                          </motion.button>
                        ))}
                      </div>
                    )}
                  </div>
                )}

                {/* Step 3: Location */}
                {currentStep === 3 && (
                  <div className="space-y-6">
                    <div>
                      <Label htmlFor="location" className="text-base font-medium text-slate-900">
                        Property Address
                      </Label>
                      <p className="text-sm text-slate-600 mb-3">
                        Enter your address or drop a pin on the map
                      </p>
                      
                      <GoogleMapsSearch
                        onLocationSelect={(location) => {
                          setWizardData({
                            ...wizardData,
                            location: {
                              address: location.address,
                              lat: location.lat,
                              lng: location.lng,
                            },
                          });
                        }}
                      />
                      
                      {wizardData.location.address && (
                        <div className="mt-4 p-4 bg-emerald-50 rounded-lg border border-emerald-200">
                          <div className="flex items-start gap-3">
                            <MapPin className="w-5 h-5 text-emerald-600 mt-0.5" />
                            <div>
                              <p className="font-medium text-emerald-900">Selected Location</p>
                              <p className="text-sm text-emerald-700">{wizardData.location.address}</p>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* Step 4: Contact Method */}
                {currentStep === 4 && (
                  <div className="space-y-6">
                    {/* Quote Summary Preview */}
                    <QuoteSummaryBox
                      projectType={PROJECT_TYPES.find(p => p.id === wizardData.projectType)?.name}
                      material={wizardData.material ? 
                        getMaterialsForProject().find(m => m.id === wizardData.material)?.name :
                        'Custom specification'
                      }
                      location={wizardData.location.address}
                      className="mb-6"
                    />
                    
                    {/* Contact Method Selection */}
                    <div>
                      <Label className="text-base font-medium text-slate-900 mb-3 block">
                        Preferred Contact Method
                      </Label>
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                        {CONTACT_METHODS.map((method) => {
                          const Icon = method.icon;
                          return (
                            <motion.button
                              key={method.id}
                              whileHover={{ scale: 1.02 }}
                              whileTap={{ scale: 0.98 }}
                              onClick={() => {
                                setWizardData({ ...wizardData, contactMethod: method.id });
                              }}
                              className={`p-4 rounded-lg border-2 transition-all ${
                                wizardData.contactMethod === method.id
                                  ? 'border-emerald-500 bg-emerald-50'
                                  : 'border-slate-200 bg-white hover:border-emerald-300'
                              }`}
                            >
                              <div className={`w-10 h-10 rounded-full bg-gradient-to-br ${method.color} flex items-center justify-center mx-auto mb-2`}>
                                <Icon className="w-5 h-5 text-white" />
                              </div>
                              <h4 className="font-semibold text-slate-900 text-sm">{method.name}</h4>
                              <p className="text-xs text-slate-600">{method.description}</p>
                              {wizardData.contactMethod === method.id && (
                                <Check className="w-5 h-5 text-emerald-600 mx-auto mt-2" />
                              )}
                            </motion.button>
                          );
                        })}
                      </div>
                    </div>

                    {/* Contact Information */}
                    <div className="space-y-4">
                      <div>
                        <Label htmlFor="name" className="text-slate-900">
                          Full Name <span className="text-red-500">*</span>
                        </Label>
                        <Input
                          id="name"
                          value={wizardData.contactInfo.name}
                          onChange={(e) =>
                            setWizardData({
                              ...wizardData,
                              contactInfo: { ...wizardData.contactInfo, name: e.target.value },
                            })
                          }
                          placeholder="John Doe"
                          className="mt-1"
                        />
                      </div>

                      <div>
                        <Label htmlFor="phone" className="text-slate-900">
                          Phone Number {wizardData.contactMethod !== 'email' && <span className="text-red-500">*</span>}
                        </Label>
                        <Input
                          id="phone"
                          value={wizardData.contactInfo.phone}
                          onChange={(e) =>
                            setWizardData({
                              ...wizardData,
                              contactInfo: { ...wizardData.contactInfo, phone: e.target.value },
                            })
                          }
                          placeholder="+27 82 123 4567"
                          className="mt-1"
                        />
                      </div>

                      <div>
                        <Label htmlFor="email" className="text-slate-900">
                          Email Address {wizardData.contactMethod !== 'phone' && wizardData.contactMethod !== 'whatsapp' && <span className="text-red-500">*</span>}
                        </Label>
                        <Input
                          id="email"
                          type="email"
                          value={wizardData.contactInfo.email}
                          onChange={(e) =>
                            setWizardData({
                              ...wizardData,
                              contactInfo: { ...wizardData.contactInfo, email: e.target.value },
                            })
                          }
                          placeholder="john@example.com"
                          className="mt-1"
                        />
                      </div>

                      <div>
                        <Label htmlFor="notes" className="text-slate-900">
                          Additional Notes (Optional)
                        </Label>
                        <Textarea
                          id="notes"
                          value={wizardData.additionalNotes}
                          onChange={(e) =>
                            setWizardData({ ...wizardData, additionalNotes: e.target.value })
                          }
                          placeholder="Any specific requirements or questions..."
                          className="mt-1"
                          rows={4}
                        />
                      </div>
                    </div>
                  </div>
                )}

                {/* Navigation Buttons */}
                <div className="flex items-center justify-between pt-6 border-t">
                  <Button
                    onClick={handleBack}
                    variant="outline"
                    disabled={currentStep === 1}
                    className="gap-2"
                  >
                    <ChevronLeft className="w-4 h-4" />
                    Back
                  </Button>

                  {currentStep < totalSteps ? (
                    <Button
                      onClick={handleNext}
                      disabled={!canProceed()}
                      className="gap-2 bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-700 hover:to-teal-700"
                    >
                      Next
                      <ChevronRight className="w-4 h-4" />
                    </Button>
                  ) : (
                    <Button
                      onClick={handleSubmit}
                      disabled={!canProceed() || isSubmitting}
                      className="gap-2 bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-700 hover:to-teal-700"
                    >
                      {isSubmitting ? (
                        <>Processing...</>
                      ) : (
                        <>
                          Submit Request
                          <Send className="w-4 h-4" />
                        </>
                      )}
                    </Button>
                  )}
                </div>
              </CardContent>
            </Card>
          </motion.div>
        </AnimatePresence>

        {/* Trust Indicators */}
        <div className="mt-8 text-center">
          <div className="flex items-center justify-center gap-6 text-white/80 text-sm">
            <div className="flex items-center gap-2">
              <Check className="w-4 h-4 text-emerald-400" />
              <span>Verified Contractors</span>
            </div>
            <div className="flex items-center gap-2">
              <Check className="w-4 h-4 text-emerald-400" />
              <span>Secure Payment</span>
            </div>
            <div className="flex items-center gap-2">
              <Check className="w-4 h-4 text-emerald-400" />
              <span>24/7 Support</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
