
'use client';

import { useState, useCallback, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter, useSearchParams } from 'next/navigation';
import { motion } from 'framer-motion';
import {
  Calculator,
  MapPin,
  Mail,
  User,
  Building2,
  Phone,
  DollarSign,
  Square,
  Waves,
  Droplets,
  Home,
  Save,
  Send,
  Loader2,
} 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { toast } from 'sonner';
import { Badge } from '@/components/ui/badge';
import { GoogleMapsSearch } from './google-maps-search';

interface Measurement {
  type: 'roof' | 'pool' | 'gutter' | 'irrigation' | 'solar_panels' | 'perimeter_walls' | 'paving';
  measurement: number;
  unit: 'sq m' | 'lm'; // square meters or linear meters
  price: number;
  notes: string;
  // Roof-specific properties
  roofType?: string;
  roofColor?: string;
  roofPitch?: number;
  pitchMultiplier?: number;
}

interface CustomerInfo {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  companyName: string;
  address: string;
}

const CURRENCIES = [
  { code: 'USD', symbol: '$', name: 'US Dollar', flag: '🇺🇸', measurementSystem: 'imperial' as const },
  { code: 'EUR', symbol: '€', name: 'Euro', flag: '🇪🇺', measurementSystem: 'metric' as const },
  { code: 'GBP', symbol: '£', name: 'British Pound', flag: '🇬🇧', measurementSystem: 'imperial' as const },
  { code: 'AUD', symbol: 'A$', name: 'Australian Dollar', flag: '🇦🇺', measurementSystem: 'metric' as const },
  { code: 'CAD', symbol: 'C$', name: 'Canadian Dollar', flag: '🇨🇦', measurementSystem: 'metric' as const },
  { code: 'JPY', symbol: '¥', name: 'Japanese Yen', flag: '🇯🇵', measurementSystem: 'metric' as const },
  { code: 'CNY', symbol: '¥', name: 'Chinese Yuan', flag: '🇨🇳', measurementSystem: 'metric' as const },
  { code: 'INR', symbol: '₹', name: 'Indian Rupee', flag: '🇮🇳', measurementSystem: 'metric' as const },
  { code: 'NZD', symbol: 'NZ$', name: 'New Zealand Dollar', flag: '🇳🇿', measurementSystem: 'metric' as const },
  { code: 'SGD', symbol: 'S$', name: 'Singapore Dollar', flag: '🇸🇬', measurementSystem: 'metric' as const },
  { code: 'HKD', symbol: 'HK$', name: 'Hong Kong Dollar', flag: '🇭🇰', measurementSystem: 'metric' as const },
  { code: 'ZAR', symbol: 'R', name: 'South African Rand', flag: '🇿🇦', measurementSystem: 'metric' as const },
  { code: 'MXN', symbol: 'MX$', name: 'Mexican Peso', flag: '🇲🇽', measurementSystem: 'metric' as const },
  { code: 'BRL', symbol: 'R$', name: 'Brazilian Real', flag: '🇧🇷', measurementSystem: 'metric' as const },
  { code: 'CHF', symbol: 'Fr', name: 'Swiss Franc', flag: '🇨🇭', measurementSystem: 'metric' as const },
] as const;

// Roof pitch options with multipliers
const ROOF_PITCHES = [
  { degrees: 0, label: 'Flat (0°)', multiplier: 1.0 },
  { degrees: 10, label: 'Low Slope (10°)', multiplier: 1.015 },
  { degrees: 15, label: 'Low (15°)', multiplier: 1.035 },
  { degrees: 22.5, label: 'Medium-Low (22.5°)', multiplier: 1.08 },
  { degrees: 30, label: 'Medium (30°)', multiplier: 1.15 },
  { degrees: 37.5, label: 'Medium-High (37.5°)', multiplier: 1.25 },
  { degrees: 45, label: 'High (45°)', multiplier: 1.41 },
  { degrees: 60, label: 'Very High (60°)', multiplier: 2.0 },
] as const;

// Roof types
const ROOF_TYPES = [
  { id: 'klip_lock', name: 'Klip Lock', baseRate: 95 },
  { id: 'corrugated', name: 'Corrugated Sheet', baseRate: 85 },
  { id: 'ibr', name: 'IBR Sheet', baseRate: 90 },
  { id: 'chromadek', name: 'Chromadek', baseRate: 100 },
  { id: 'tile', name: 'Roof Tile', baseRate: 120 },
] as const;

// Roof colors based on the uploaded chart with price adjustments
const ROOF_COLORS = [
  // White shades
  { name: 'African White AZ180', code: 'AZ180-82', hexColor: '#F5F5F5', priceModifier: 0 },
  { name: 'Amazing White AZ200', code: 'AZ200-82', hexColor: '#FAFAFA', priceModifier: 2 },
  { name: 'Cape White AZ180', code: 'AZ180-78', hexColor: '#F0EAD6', priceModifier: 0 },
  { name: 'Cederberg White AZ200', code: 'AZ200-78', hexColor: '#EDE6D5', priceModifier: 2 },
  { name: 'Off White AZ180', code: 'AZ180-80', hexColor: '#FAF0E6', priceModifier: 0 },
  { name: 'Enduring White AZ200', code: 'AZ200-80', hexColor: '#FFF8F0', priceModifier: 2 },
  
  // Cream shades
  { name: 'African Cream AZ180', code: 'AZ180-71', hexColor: '#F5DEB3', priceModifier: 1 },
  { name: 'Orange Cream AZ200', code: 'AZ200-71', hexColor: '#FFE4B5', priceModifier: 3 },
  
  // Grey shades
  { name: 'Shale Grey AZ180', code: 'AZ180-66', hexColor: '#A9A9A9', priceModifier: 1 },
  { name: 'Ultimate Grey AZ200', code: 'AZ200-66', hexColor: '#B0B0B0', priceModifier: 3 },
  { name: 'Armour Grey AZ180', code: 'AZ180-48', hexColor: '#808080', priceModifier: 2 },
  { name: 'Livid Grey AZ200', code: 'AZ200-48', hexColor: '#898989', priceModifier: 4 },
  { name: 'Volcanic Grey AZ180', code: 'AZ180-38', hexColor: '#505050', priceModifier: 3 },
  { name: 'Ore Grey AZ200', code: 'AZ200-38', hexColor: '#585858', priceModifier: 5 },
  { name: 'Dune AZ180', code: 'AZ180-62', hexColor: '#C4B5A0', priceModifier: 1 },
  { name: 'Sahara Sands AZ200', code: 'AZ200-62', hexColor: '#D2B48C', priceModifier: 3 },
  
  // Dark shades
  { name: 'Cape Charcoal AZ180', code: 'AZ180-20', hexColor: '#36454F', priceModifier: 4 },
  { name: 'African Charcoal AZ200', code: 'AZ200-20', hexColor: '#3C4448', priceModifier: 6 },
  
  // Red/Brown shades
  { name: 'Heritage Red AZ180', code: 'AZ180-32', hexColor: '#8B0000', priceModifier: 3 },
  { name: 'Enchanting Red AZ200', code: 'AZ200-32', hexColor: '#DC143C', priceModifier: 5 },
  
  // Blue shades
  { name: 'African Blue AZ180', code: 'AZ180-27', hexColor: '#003366', priceModifier: 4 },
  { name: 'Two Oceans Blue AZ200', code: 'AZ200-27', hexColor: '#004E8A', priceModifier: 6 },
  
  // Green shades
  { name: 'Colonial Green AZ180', code: 'AZ180-26', hexColor: '#2F4F2F', priceModifier: 3 },
  { name: 'Garden Route Green AZ200', code: 'AZ200-26', hexColor: '#355E3B', priceModifier: 5 },
] as const;

export function QuoteGeneratorClient() {
  const { data: session } = useSession() || {};
  const router = useRouter();
  const searchParams = useSearchParams();
  const [activeTab, setActiveTab] = useState('customer');
  const [isLoading, setIsLoading] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [transferAddress, setTransferAddress] = useState(false);
  const [addressToTransfer, setAddressToTransfer] = useState('');
  const [contingency, setContingency] = useState(5); // Default 5% contingency
  const [measurementUnit, setMeasurementUnit] = useState<'metric' | 'imperial'>('metric');

  const [customerInfo, setCustomerInfo] = useState<CustomerInfo>({
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    companyName: '',
    address: '',
  });

  // Load default currency from localStorage
  const [currency, setCurrency] = useState(() => {
    if (typeof window !== 'undefined') {
      return localStorage.getItem('defaultCurrency') || 'USD';
    }
    return 'USD';
  });

  // Load customer data from URL parameters
  useEffect(() => {
    const firstName = searchParams?.get('firstName');
    const lastName = searchParams?.get('lastName');
    const email = searchParams?.get('email');
    const phone = searchParams?.get('phone');
    const companyName = searchParams?.get('companyName');
    const address = searchParams?.get('address');

    if (firstName || lastName || email) {
      setCustomerInfo({
        firstName: firstName || '',
        lastName: lastName || '',
        email: email || '',
        phone: phone || '',
        companyName: companyName || '',
        address: address || '',
      });

      if (address) {
        setAddressToTransfer(address);
        toast.success('Customer information loaded');
      }
    }
  }, [searchParams]);

  // Auto-switch measurement unit based on currency
  useEffect(() => {
    const selectedCurrency = CURRENCIES.find(c => c.code === currency);
    if (selectedCurrency) {
      setMeasurementUnit(selectedCurrency.measurementSystem);
    }
  }, [currency]);
  const [measurements, setMeasurements] = useState<Measurement[]>([]);
  const [currentMeasurement, setCurrentMeasurement] = useState<{
    type: 'roof' | 'pool' | 'gutter' | 'irrigation' | 'solar_panels' | 'perimeter_walls' | 'paving';
    measurement: number;
    unit: 'sq m' | 'lm';
    price: number;
    notes: string;
    roofType?: string;
    roofColor?: string;
    roofPitch?: number;
    pitchMultiplier?: number;
  }>({
    type: 'roof',
    measurement: 0,
    unit: 'sq m',
    price: 0,
    notes: '',
    roofType: 'klip_lock',
    roofColor: ROOF_COLORS[0].name,
    roofPitch: 30,
    pitchMultiplier: 1.15,
  });

  const [quoteDetails, setQuoteDetails] = useState({
    projectType: 'roofing',
    description: '',
    validUntil: '',
    terms: 'Payment due within 30 days of acceptance. 50% deposit required to commence work.',
  });

  // Pricing rates per unit (square meter or linear meter) - loaded from database
  const [rates, setRates] = useState({
    roof: 85,              // per sq m
    pool: 120,             // per sq m
    gutter: 45,            // per linear meter
    irrigation: 95,        // per sq m
    solar_panels: 150,     // per sq m
    perimeter_walls: 55,   // per linear meter
    paving: 75,            // per sq m
  });
  const [showPricingEditor, setShowPricingEditor] = useState(false);
  const [isSavingRates, setIsSavingRates] = useState(false);

  // Fetch pricing rates from database on mount
  useEffect(() => {
    const fetchRates = async () => {
      try {
        const response = await fetch('/api/pricing');
        if (response.ok) {
          const data = await response.json();
          const ratesMap: any = {};
          data.rates.forEach((rate: any) => {
            ratesMap[rate.serviceType] = rate.rate;
          });
          setRates(ratesMap);
        }
      } catch (error) {
        console.error('Error fetching pricing rates:', error);
      }
    };

    fetchRates();
  }, []);

  // Get currency symbol
  const getCurrencySymbol = () => {
    return CURRENCIES.find(c => c.code === currency)?.symbol || '$';
  };

  // Handle currency change
  const handleCurrencyChange = (newCurrency: string) => {
    setCurrency(newCurrency);
    const selectedCurrency = CURRENCIES.find(c => c.code === newCurrency);
    if (selectedCurrency) {
      toast.success(`Currency changed to ${selectedCurrency.name}. Measurement unit auto-switched to ${selectedCurrency.measurementSystem}.`);
    }
  };

  // Save as default currency
  const handleSetDefaultCurrency = () => {
    if (typeof window !== 'undefined') {
      localStorage.setItem('defaultCurrency', currency);
      toast.success(`${currency} set as default currency`);
    }
  };

  // Update measurement type and unit
  const handleTypeChange = (type: 'roof' | 'pool' | 'gutter' | 'irrigation' | 'solar_panels' | 'perimeter_walls' | 'paving') => {
    const unit = (type === 'gutter' || type === 'perimeter_walls') ? 'lm' : 'sq m';
    setCurrentMeasurement({
      ...currentMeasurement,
      type,
      unit,
    });
  };

  // Calculate roof price based on type, color, and pitch
  const calculateRoofPrice = (
    area: number,
    roofType: string,
    roofColor: string,
    pitchMultiplier: number
  ) => {
    const type = ROOF_TYPES.find(t => t.id === roofType);
    const color = ROOF_COLORS.find(c => c.name === roofColor);
    
    if (!type || !color) return area * rates.roof;
    
    // Base rate from roof type + color modifier, then apply pitch multiplier
    const basePrice = type.baseRate + color.priceModifier;
    return area * basePrice * pitchMultiplier;
  };

  const handleAddMeasurement = () => {
    if (currentMeasurement.measurement <= 0) {
      toast.error('Please enter a valid measurement');
      return;
    }

    let price = 0;
    
    // Calculate price based on measurement type
    if (currentMeasurement.type === 'roof' && currentMeasurement.roofType && currentMeasurement.roofColor && currentMeasurement.pitchMultiplier) {
      price = calculateRoofPrice(
        currentMeasurement.measurement,
        currentMeasurement.roofType,
        currentMeasurement.roofColor,
        currentMeasurement.pitchMultiplier
      );
    } else {
      price = currentMeasurement.measurement * rates[currentMeasurement.type];
    }

    const newMeasurement: Measurement = {
      ...currentMeasurement,
      price,
    };

    setMeasurements([...measurements, newMeasurement]);
    setCurrentMeasurement({
      type: 'roof',
      measurement: 0,
      unit: 'sq m',
      price: 0,
      notes: '',
      roofType: 'klip_lock',
      roofColor: ROOF_COLORS[0].name,
      roofPitch: 30,
      pitchMultiplier: 1.15,
    });
    toast.success('Measurement added successfully');
  };

  const handleRemoveMeasurement = (index: number) => {
    setMeasurements(measurements.filter((_, i) => i !== index));
    toast.success('Measurement removed');
  };

  const calculateTotal = () => {
    return measurements.reduce((sum, m) => sum + m.price, 0);
  };

  const handleSaveRates = async () => {
    if (session?.user.role !== 'ADMIN') {
      toast.error('Only administrators can update pricing rates');
      return;
    }

    setIsSavingRates(true);
    try {
      const ratesArray = Object.entries(rates).map(([serviceType, rate]) => ({
        serviceType,
        rate,
        unit: (serviceType === 'gutter' || serviceType === 'perimeter_walls') ? 'lm' : 'sq m',
        currency: currency,
        description: `${serviceType.replace(/_/g, ' ')} service rate`
      }));

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

      if (response.ok) {
        toast.success('Pricing rates updated successfully');
        setShowPricingEditor(false);
      } else {
        throw new Error('Failed to update rates');
      }
    } catch (error) {
      console.error('Error saving pricing rates:', error);
      toast.error('Failed to save pricing rates');
    } finally {
      setIsSavingRates(false);
    }
  };

  const handleLocationSelect = useCallback((location: { address: string; lat: number; lng: number }) => {
    setCustomerInfo(prev => ({ ...prev, address: location.address }));
    toast.success('Location selected');
  }, []);

  const handleAreaMeasured = useCallback((area: number) => {
    setCurrentMeasurement(prev => ({ 
      ...prev, 
      measurement: area,
      unit: 'sq m'
    }));
  }, []);

  const handleLineMeasured = useCallback((length: number) => {
    setCurrentMeasurement(prev => {
      // If current type is not already a linear type, default to gutter
      const currentType = prev.type;
      const newType = (currentType === 'gutter' || currentType === 'perimeter_walls') ? currentType : 'gutter';
      return { 
        ...prev, 
        measurement: length,
        unit: 'lm',
        type: newType
      };
    });
  }, []);

  const validateForm = () => {
    if (!customerInfo.firstName || !customerInfo.lastName || !customerInfo.email) {
      toast.error('Please fill in all required customer information');
      return false;
    }

    if (measurements.length === 0) {
      toast.error('Please add at least one measurement');
      return false;
    }

    return true;
  };

  const handleSaveQuote = async (sendEmail = false) => {
    if (!validateForm()) return;

    setIsSaving(true);

    try {
      const response = await fetch('/api/quotes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          customerInfo,
          measurements,
          quoteDetails,
          totalAmount: calculateTotal(),
          currency,
          sendEmail,
        }),
      });

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

      const data = await response.json();
      
      toast.success(
        sendEmail 
          ? 'Quote created and sent to customer!'
          : 'Quote saved successfully!'
      );

      router.push('/dashboard');
    } catch (error) {
      console.error('Error saving quote:', error);
      toast.error('Failed to save quote. Please try again.');
    } finally {
      setIsSaving(false);
    }
  };

  const total = calculateTotal();

  return (
    <div className="container mx-auto py-8 space-y-6">
      {/* Header */}
      <motion.div
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4 }}
      >
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold gradient-text flex items-center gap-2">
              <Calculator className="w-8 h-8" />
              Create New Quote
            </h1>
            <p className="text-muted-foreground mt-1">
              Use Google Maps to measure areas and generate accurate quotes
            </p>
          </div>
          <div className="flex items-center gap-3">
            <div className="flex flex-col items-end gap-2">
              <Label className="text-xs">Currency</Label>
              <div className="flex gap-2">
                <Select value={currency} onValueChange={handleCurrencyChange}>
                  <SelectTrigger className="w-[220px]">
                    <SelectValue>
                      {CURRENCIES.find(c => c.code === currency) && (
                        <span className="flex items-center gap-2">
                          <span>{CURRENCIES.find(c => c.code === currency)?.flag}</span>
                          <span>{CURRENCIES.find(c => c.code === currency)?.symbol} {currency}</span>
                        </span>
                      )}
                    </SelectValue>
                  </SelectTrigger>
                  <SelectContent>
                    {CURRENCIES.map(curr => (
                      <SelectItem key={curr.code} value={curr.code}>
                        {curr.flag} {curr.symbol} {curr.code} - {curr.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleSetDefaultCurrency}
                  title="Set as default currency"
                  className="whitespace-nowrap"
                >
                  Set Default
                </Button>
              </div>
              <Badge variant="secondary" className="text-xs">
                {CURRENCIES.find(c => c.code === currency)?.flag} {currency} - {measurementUnit === 'metric' ? 'Metric' : 'Imperial'}
              </Badge>
            </div>
            <Button variant="outline" onClick={() => router.push('/dashboard')}>
              Cancel
            </Button>
          </div>
        </div>
      </motion.div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main Form */}
        <div className="lg:col-span-2 space-y-6">
          <Tabs value={activeTab} onValueChange={setActiveTab}>
            <TabsList className="grid w-full grid-cols-3">
              <TabsTrigger value="customer">Customer Info</TabsTrigger>
              <TabsTrigger value="measurements">Measurements</TabsTrigger>
              <TabsTrigger value="details">Quote Details</TabsTrigger>
            </TabsList>

            {/* Customer Information Tab */}
            <TabsContent value="customer">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <User className="w-5 h-5" />
                    Customer Information
                  </CardTitle>
                  <CardDescription>Enter the customer's contact details</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="firstName">First Name *</Label>
                      <Input
                        id="firstName"
                        value={customerInfo.firstName}
                        onChange={(e) => setCustomerInfo({ ...customerInfo, firstName: e.target.value })}
                        placeholder="John"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="lastName">Last Name *</Label>
                      <Input
                        id="lastName"
                        value={customerInfo.lastName}
                        onChange={(e) => setCustomerInfo({ ...customerInfo, lastName: e.target.value })}
                        placeholder="Doe"
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="email">Email *</Label>
                    <Input
                      id="email"
                      type="email"
                      value={customerInfo.email}
                      onChange={(e) => setCustomerInfo({ ...customerInfo, email: e.target.value })}
                      placeholder="john.doe@example.com"
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="phone">Phone Number</Label>
                    <Input
                      id="phone"
                      type="tel"
                      value={customerInfo.phone}
                      onChange={(e) => setCustomerInfo({ ...customerInfo, phone: e.target.value })}
                      placeholder="+1 (555) 123-4567"
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="companyName">Company Name</Label>
                    <Input
                      id="companyName"
                      value={customerInfo.companyName}
                      onChange={(e) => setCustomerInfo({ ...customerInfo, companyName: e.target.value })}
                      placeholder="ABC Corporation"
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="address">Project Address</Label>
                    <Input
                      id="address"
                      value={customerInfo.address}
                      onChange={(e) => setCustomerInfo({ ...customerInfo, address: e.target.value })}
                      placeholder="123 Main Street, City, State"
                    />
                  </div>

                  <div className="space-y-3">
                    {customerInfo.address && (
                      <div className="flex items-center gap-2 p-3 bg-primary/5 rounded-lg">
                        <MapPin className="w-4 h-4 text-primary" />
                        <span className="text-sm text-muted-foreground">
                          Address will be transferred to map: <span className="font-medium text-foreground">{customerInfo.address}</span>
                        </span>
                      </div>
                    )}
                    
                    <Button 
                      onClick={() => {
                        if (customerInfo.address) {
                          setAddressToTransfer(customerInfo.address);
                          setTransferAddress(true);
                          toast.success('Address will be loaded in Google Maps');
                        }
                        setActiveTab('measurements');
                      }} 
                      className="w-full"
                    >
                      {customerInfo.address ? 'Next: Add Measurements (with address)' : 'Next: Add Measurements'}
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            {/* Measurements Tab */}
            <TabsContent value="measurements">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Square className="w-5 h-5" />
                    Area Measurements
                  </CardTitle>
                  <CardDescription>
                    Add measurements for different project areas
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                  {/* Google Maps Integration */}
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <Label>Search Location & Measure Area</Label>
                      {addressToTransfer && (
                        <Badge variant="secondary" className="flex items-center gap-1">
                          <MapPin className="w-3 h-3" />
                          Address loaded
                        </Badge>
                      )}
                    </div>
                    <GoogleMapsSearch
                      initialAddress={transferAddress ? addressToTransfer : undefined}
                      onLocationSelect={handleLocationSelect}
                      onAreaMeasured={handleAreaMeasured}
                      onLineMeasured={handleLineMeasured}
                      onAddressUsed={() => setTransferAddress(false)}
                      contingency={contingency}
                      onContingencyChange={setContingency}
                      measurementUnit={measurementUnit}
                      onMeasurementUnitChange={setMeasurementUnit}
                    />
                  </div>

                  {/* Manual Entry */}
                  <div className="space-y-4 pt-4 border-t">
                    <Label>Add Measurement</Label>
                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="measurementType">Type</Label>
                        <Select
                          value={currentMeasurement.type}
                          onValueChange={handleTypeChange}
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="roof">
                              <div className="flex items-center gap-2">
                                <Home className="w-4 h-4" />
                                Roofing (Price varies by type & color)
                              </div>
                            </SelectItem>
                            <SelectItem value="pool">
                              <div className="flex items-center gap-2">
                                <Waves className="w-4 h-4" />
                                Pool ({getCurrencySymbol()}{rates.pool}/sq m)
                              </div>
                            </SelectItem>
                            <SelectItem value="gutter">
                              <div className="flex items-center gap-2">
                                <Droplets className="w-4 h-4" />
                                Gutter ({getCurrencySymbol()}{rates.gutter}/lm)
                              </div>
                            </SelectItem>
                            <SelectItem value="irrigation">
                              <div className="flex items-center gap-2">
                                <Square className="w-4 h-4" />
                                Irrigation ({getCurrencySymbol()}{rates.irrigation}/sq m)
                              </div>
                            </SelectItem>
                            <SelectItem value="solar_panels">
                              <div className="flex items-center gap-2">
                                <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                  <rect x="2" y="2" width="20" height="20" rx="2" />
                                  <line x1="7" y1="2" x2="7" y2="22" />
                                  <line x1="12" y1="2" x2="12" y2="22" />
                                  <line x1="17" y1="2" x2="17" y2="22" />
                                  <line x1="2" y1="7" x2="22" y2="7" />
                                  <line x1="2" y1="12" x2="22" y2="12" />
                                  <line x1="2" y1="17" x2="22" y2="17" />
                                </svg>
                                Solar Panels ({getCurrencySymbol()}{rates.solar_panels}/sq m)
                              </div>
                            </SelectItem>
                            <SelectItem value="perimeter_walls">
                              <div className="flex items-center gap-2">
                                <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                  <path d="M3 3h18v18H3V3z M3 9h18 M3 15h18 M9 3v18 M15 3v18" />
                                </svg>
                                Perimeter Walls ({getCurrencySymbol()}{rates.perimeter_walls}/lm)
                              </div>
                            </SelectItem>
                            <SelectItem value="paving">
                              <div className="flex items-center gap-2">
                                <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                  <rect x="4" y="4" width="7" height="7" />
                                  <rect x="13" y="4" width="7" height="7" />
                                  <rect x="4" y="13" width="7" height="7" />
                                  <rect x="13" y="13" width="7" height="7" />
                                </svg>
                                Paving ({getCurrencySymbol()}{rates.paving}/sq m)
                              </div>
                            </SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      <div className="space-y-2">
                        <Label htmlFor="measurement">
                          {currentMeasurement.type === 'gutter' ? 'Length' : 'Area'} ({currentMeasurement.unit})
                        </Label>
                        <Input
                          id="measurement"
                          type="number"
                          step="0.01"
                          value={currentMeasurement.measurement || ''}
                          onChange={(e) =>
                            setCurrentMeasurement({
                              ...currentMeasurement,
                              measurement: parseFloat(e.target.value) || 0,
                            })
                          }
                          placeholder="0.00"
                        />
                      </div>
                    </div>

                    {/* Roof-specific options */}
                    {currentMeasurement.type === 'roof' && (
                      <div className="space-y-4 p-4 bg-blue-50 dark:bg-blue-950/20 rounded-lg border border-blue-200 dark:border-blue-800">
                        <div className="flex items-center gap-2 mb-2">
                          <Home className="w-4 h-4 text-blue-600" />
                          <Label className="text-blue-900 dark:text-blue-100 font-semibold">Roofing Configuration</Label>
                        </div>
                        
                        <div className="grid grid-cols-2 gap-4">
                          <div className="space-y-2">
                            <Label htmlFor="roofType">Roof Type</Label>
                            <Select
                              value={currentMeasurement.roofType}
                              onValueChange={(value) =>
                                setCurrentMeasurement({ ...currentMeasurement, roofType: value })
                              }
                            >
                              <SelectTrigger>
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                {ROOF_TYPES.map((type) => (
                                  <SelectItem key={type.id} value={type.id}>
                                    {type.name} ({getCurrencySymbol()}{type.baseRate}/sq m)
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>

                          <div className="space-y-2">
                            <Label htmlFor="roofPitch">Roof Pitch</Label>
                            <Select
                              value={currentMeasurement.roofPitch?.toString()}
                              onValueChange={(value) => {
                                const pitch = ROOF_PITCHES.find(p => p.degrees.toString() === value);
                                setCurrentMeasurement({ 
                                  ...currentMeasurement, 
                                  roofPitch: parseInt(value),
                                  pitchMultiplier: pitch?.multiplier || 1.0
                                });
                              }}
                            >
                              <SelectTrigger>
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                {ROOF_PITCHES.map((pitch) => (
                                  <SelectItem key={pitch.degrees} value={pitch.degrees.toString()}>
                                    {pitch.label} (×{pitch.multiplier})
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>
                        </div>

                        <div className="space-y-2">
                          <Label htmlFor="roofColor">Roof Color</Label>
                          <Select
                            value={currentMeasurement.roofColor}
                            onValueChange={(value) =>
                              setCurrentMeasurement({ ...currentMeasurement, roofColor: value })
                            }
                          >
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent className="max-h-[300px]">
                              {ROOF_COLORS.map((color) => (
                                <SelectItem key={color.code} value={color.name}>
                                  <div className="flex items-center gap-2">
                                    <div 
                                      className="w-6 h-6 rounded border border-gray-300"
                                      style={{ backgroundColor: color.hexColor }}
                                    />
                                    <span>{color.name}</span>
                                    <span className="text-xs text-muted-foreground">
                                      (+{getCurrencySymbol()}{color.priceModifier})
                                    </span>
                                  </div>
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>

                        {/* Price Preview */}
                        {currentMeasurement.measurement > 0 && currentMeasurement.roofType && currentMeasurement.roofColor && currentMeasurement.pitchMultiplier && (
                          <div className="p-3 bg-white dark:bg-gray-900 rounded border">
                            <div className="text-sm space-y-1">
                              <div className="flex justify-between">
                                <span className="text-muted-foreground">Base Rate:</span>
                                <span className="font-medium">
                                  {getCurrencySymbol()}
                                  {(ROOF_TYPES.find(t => t.id === currentMeasurement.roofType)?.baseRate || 0) + 
                                   (ROOF_COLORS.find(c => c.name === currentMeasurement.roofColor)?.priceModifier || 0)}
                                  /sq m
                                </span>
                              </div>
                              <div className="flex justify-between">
                                <span className="text-muted-foreground">Area:</span>
                                <span className="font-medium">{currentMeasurement.measurement.toFixed(2)} sq m</span>
                              </div>
                              <div className="flex justify-between">
                                <span className="text-muted-foreground">Pitch Multiplier:</span>
                                <span className="font-medium">×{currentMeasurement.pitchMultiplier}</span>
                              </div>
                              <div className="flex justify-between pt-2 border-t font-bold text-lg">
                                <span>Estimated Total:</span>
                                <span className="text-primary">
                                  {getCurrencySymbol()}
                                  {calculateRoofPrice(
                                    currentMeasurement.measurement,
                                    currentMeasurement.roofType,
                                    currentMeasurement.roofColor,
                                    currentMeasurement.pitchMultiplier
                                  ).toFixed(2)}
                                </span>
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    )}

                    <div className="space-y-2">
                      <Label htmlFor="notes">Notes</Label>
                      <Textarea
                        id="notes"
                        value={currentMeasurement.notes}
                        onChange={(e) =>
                          setCurrentMeasurement({ ...currentMeasurement, notes: e.target.value })
                        }
                        placeholder="Additional notes about this measurement..."
                        rows={2}
                      />
                    </div>

                    <Button onClick={handleAddMeasurement} className="w-full">
                      Add Measurement
                    </Button>
                  </div>

                  {/* Added Measurements List */}
                  {measurements.length > 0 && (
                    <div className="space-y-2 pt-4 border-t">
                      <Label>Added Measurements</Label>
                      <div className="space-y-2">
                        {measurements.map((m, index) => (
                          <div
                            key={index}
                            className="p-3 bg-muted rounded-lg"
                          >
                            <div className="flex items-center justify-between mb-2">
                              <div className="flex items-center gap-2 flex-1">
                                <Badge variant="outline" className="capitalize">
                                  {m.type}
                                </Badge>
                                <span className="font-medium">
                                  {m.measurement.toFixed(2)} {m.unit}
                                </span>
                              </div>
                              <div className="flex items-center gap-3">
                                <span className="font-semibold text-lg">
                                  {getCurrencySymbol()}{m.price.toFixed(2)}
                                </span>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => handleRemoveMeasurement(index)}
                                >
                                  Remove
                                </Button>
                              </div>
                            </div>
                            
                            {/* Show roof details if it's a roof measurement */}
                            {m.type === 'roof' && m.roofType && m.roofColor && (
                              <div className="flex flex-wrap gap-2 mt-2 pt-2 border-t border-border/50">
                                <Badge variant="secondary" className="text-xs">
                                  {ROOF_TYPES.find(t => t.id === m.roofType)?.name}
                                </Badge>
                                <Badge 
                                  variant="secondary" 
                                  className="text-xs flex items-center gap-1"
                                >
                                  <div 
                                    className="w-3 h-3 rounded-sm border border-gray-400"
                                    style={{ 
                                      backgroundColor: ROOF_COLORS.find(c => c.name === m.roofColor)?.hexColor 
                                    }}
                                  />
                                  {m.roofColor}
                                </Badge>
                                <Badge variant="secondary" className="text-xs">
                                  Pitch: {m.roofPitch}° (×{m.pitchMultiplier})
                                </Badge>
                              </div>
                            )}
                            
                            {m.notes && (
                              <p className="text-xs text-muted-foreground mt-2">{m.notes}</p>
                            )}
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  <Button 
                    onClick={() => setActiveTab('details')} 
                    className="w-full"
                    disabled={measurements.length === 0}
                  >
                    Next: Quote Details
                  </Button>
                </CardContent>
              </Card>
            </TabsContent>

            {/* Quote Details Tab */}
            <TabsContent value="details">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Calculator className="w-5 h-5" />
                    Quote Details
                  </CardTitle>
                  <CardDescription>Add project description and terms</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="space-y-2">
                    <Label htmlFor="projectType">Project Type</Label>
                    <Select
                      value={quoteDetails.projectType}
                      onValueChange={(value) =>
                        setQuoteDetails({ ...quoteDetails, projectType: value })
                      }
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="roofing">Roofing</SelectItem>
                        <SelectItem value="pool">Pool Installation/Maintenance</SelectItem>
                        <SelectItem value="gutter">Gutter Work</SelectItem>
                        <SelectItem value="irrigation">Irrigation System</SelectItem>
                        <SelectItem value="mixed">Mixed Services</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="description">Project Description</Label>
                    <Textarea
                      id="description"
                      value={quoteDetails.description}
                      onChange={(e) =>
                        setQuoteDetails({ ...quoteDetails, description: e.target.value })
                      }
                      placeholder="Describe the project scope, materials, and any special requirements..."
                      rows={4}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="validUntil">Valid Until</Label>
                    <Input
                      id="validUntil"
                      type="date"
                      value={quoteDetails.validUntil}
                      onChange={(e) =>
                        setQuoteDetails({ ...quoteDetails, validUntil: e.target.value })
                      }
                      min={new Date().toISOString().split('T')[0]}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="terms">Terms & Conditions</Label>
                    <Textarea
                      id="terms"
                      value={quoteDetails.terms}
                      onChange={(e) =>
                        setQuoteDetails({ ...quoteDetails, terms: e.target.value })
                      }
                      placeholder="Payment terms, warranties, and other conditions..."
                      rows={3}
                    />
                  </div>

                  <div className="flex gap-2">
                    <Button
                      onClick={() => handleSaveQuote(false)}
                      disabled={isSaving}
                      variant="outline"
                      className="flex-1"
                    >
                      {isSaving ? (
                        <>
                          <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                          Saving...
                        </>
                      ) : (
                        <>
                          <Save className="w-4 h-4 mr-2" />
                          Save as Draft
                        </>
                      )}
                    </Button>
                    <Button
                      onClick={() => handleSaveQuote(true)}
                      disabled={isSaving}
                      className="flex-1"
                    >
                      {isSaving ? (
                        <>
                          <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                          Sending...
                        </>
                      ) : (
                        <>
                          <Send className="w-4 h-4 mr-2" />
                          Save & Send Email
                        </>
                      )}
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>
        </div>

        {/* Summary Panel */}
        <div className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Quote Summary</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {customerInfo.firstName && (
                <div>
                  <Label className="text-xs text-muted-foreground">Customer</Label>
                  <p className="font-medium">
                    {customerInfo.firstName} {customerInfo.lastName}
                  </p>
                  {customerInfo.email && (
                    <p className="text-sm text-muted-foreground">{customerInfo.email}</p>
                  )}
                </div>
              )}

              <div className="border-t pt-4">
                <Label className="text-xs text-muted-foreground">Measurements</Label>
                <div className="space-y-2 mt-2">
                  {measurements.length === 0 ? (
                    <p className="text-sm text-muted-foreground">No measurements added yet</p>
                  ) : (
                    measurements.map((m, index) => (
                      <div key={index} className="space-y-1">
                        <div className="flex justify-between text-sm">
                          <span className="capitalize font-medium">{m.type} ({m.measurement.toFixed(2)} {m.unit})</span>
                          <span className="font-semibold">{getCurrencySymbol()}{m.price.toFixed(2)}</span>
                        </div>
                        {m.type === 'roof' && m.roofType && m.roofColor && (
                          <div className="flex items-center gap-1 text-xs text-muted-foreground pl-2">
                            <div 
                              className="w-2 h-2 rounded-sm border border-gray-400"
                              style={{ 
                                backgroundColor: ROOF_COLORS.find(c => c.name === m.roofColor)?.hexColor 
                              }}
                            />
                            {ROOF_TYPES.find(t => t.id === m.roofType)?.name} • {m.roofPitch}°
                          </div>
                        )}
                      </div>
                    ))
                  )}
                </div>
              </div>

              <div className="border-t pt-4 space-y-2">
                <div className="flex justify-between items-center">
                  <Label>Total Amount</Label>
                  <span className="text-2xl font-bold text-primary">
                    {getCurrencySymbol()}{total.toFixed(2)}
                  </span>
                </div>
                <p className="text-xs text-muted-foreground">Currency: {currency}</p>
                <div className="bg-blue-50 dark:bg-blue-950/20 p-2 rounded">
                  <p className="text-xs text-blue-900 dark:text-blue-100">
                    <strong>Contingency:</strong> {contingency}% included in measurements
                  </p>
                </div>
              </div>

              {quoteDetails.validUntil && (
                <div className="bg-muted p-3 rounded-lg">
                  <Label className="text-xs">Valid Until</Label>
                  <p className="font-medium">
                    {new Date(quoteDetails.validUntil).toLocaleDateString('en-US', {
                      year: 'numeric',
                      month: 'long',
                      day: 'numeric',
                    })}
                  </p>
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="text-base">Pricing Rates</CardTitle>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setShowPricingEditor(!showPricingEditor)}
                >
                  {showPricingEditor ? 'Hide' : 'Edit'}
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              {showPricingEditor ? (
                <div className="space-y-3">
                  <div className="space-y-2">
                    <Label htmlFor="rate-roof" className="text-sm">Roofing (per sq m)</Label>
                    <Input
                      id="rate-roof"
                      type="number"
                      step="0.01"
                      value={rates.roof}
                      onChange={(e) => setRates({ ...rates, roof: parseFloat(e.target.value) || 0 })}
                      className="h-8"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="rate-pool" className="text-sm">Pool (per sq m)</Label>
                    <Input
                      id="rate-pool"
                      type="number"
                      step="0.01"
                      value={rates.pool}
                      onChange={(e) => setRates({ ...rates, pool: parseFloat(e.target.value) || 0 })}
                      className="h-8"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="rate-gutter" className="text-sm">Gutter (per lm)</Label>
                    <Input
                      id="rate-gutter"
                      type="number"
                      step="0.01"
                      value={rates.gutter}
                      onChange={(e) => setRates({ ...rates, gutter: parseFloat(e.target.value) || 0 })}
                      className="h-8"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="rate-irrigation" className="text-sm">Irrigation (per sq m)</Label>
                    <Input
                      id="rate-irrigation"
                      type="number"
                      step="0.01"
                      value={rates.irrigation}
                      onChange={(e) => setRates({ ...rates, irrigation: parseFloat(e.target.value) || 0 })}
                      className="h-8"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="rate-solar" className="text-sm">Solar Panels (per sq m)</Label>
                    <Input
                      id="rate-solar"
                      type="number"
                      step="0.01"
                      value={rates.solar_panels}
                      onChange={(e) => setRates({ ...rates, solar_panels: parseFloat(e.target.value) || 0 })}
                      className="h-8"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="rate-walls" className="text-sm">Perimeter Walls (per lm)</Label>
                    <Input
                      id="rate-walls"
                      type="number"
                      step="0.01"
                      value={rates.perimeter_walls}
                      onChange={(e) => setRates({ ...rates, perimeter_walls: parseFloat(e.target.value) || 0 })}
                      className="h-8"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="rate-paving" className="text-sm">Paving (per sq m)</Label>
                    <Input
                      id="rate-paving"
                      type="number"
                      step="0.01"
                      value={rates.paving}
                      onChange={(e) => setRates({ ...rates, paving: parseFloat(e.target.value) || 0 })}
                      className="h-8"
                    />
                  </div>
                  
                  {session?.user.role === 'ADMIN' && (
                    <div className="pt-4 border-t flex gap-2">
                      <Button
                        onClick={handleSaveRates}
                        disabled={isSavingRates}
                        size="sm"
                        className="flex-1"
                      >
                        {isSavingRates ? (
                          <>
                            <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                            Saving...
                          </>
                        ) : (
                          <>
                            <Save className="w-4 h-4 mr-2" />
                            Save Rates
                          </>
                        )}
                      </Button>
                      <Button
                        onClick={() => setShowPricingEditor(false)}
                        variant="outline"
                        size="sm"
                      >
                        Cancel
                      </Button>
                    </div>
                  )}
                </div>
              ) : (
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span>Roofing</span>
                    <span className="font-medium">{getCurrencySymbol()}{rates.roof}/sq m</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Pool</span>
                    <span className="font-medium">{getCurrencySymbol()}{rates.pool}/sq m</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Gutter</span>
                    <span className="font-medium">{getCurrencySymbol()}{rates.gutter}/lm</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Irrigation</span>
                    <span className="font-medium">{getCurrencySymbol()}{rates.irrigation}/sq m</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Solar Panels</span>
                    <span className="font-medium">{getCurrencySymbol()}{rates.solar_panels}/sq m</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Perimeter Walls</span>
                    <span className="font-medium">{getCurrencySymbol()}{rates.perimeter_walls}/lm</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Paving</span>
                    <span className="font-medium">{getCurrencySymbol()}{rates.paving}/sq m</span>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
