
'use client';

import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { motion } from 'framer-motion';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Checkbox } from '@/components/ui/checkbox';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { toast } from 'sonner';
import { Loader2, CheckCircle, User, MapPin, Phone, Mail, DollarSign, Calendar, Tag, InfoIcon } from 'lucide-react';

const leadSchema = z.object({
  firstName: z.string().min(1, 'First name is required'),
  lastName: z.string().min(1, 'Last name is required'),
  email: z.string().email('Invalid email address'),
  phone: z.string().min(10, 'Phone number must be at least 10 characters'),
  address: z.string().min(1, 'Address is required'),
  city: z.string().min(1, 'City is required'),
  state: z.string().min(2, 'State is required'),
  zipCode: z.string().min(5, 'ZIP code must be at least 5 characters'),
  source: z.string().min(1, 'Lead source is required'),
  services: z.array(z.string()).min(1, 'Select at least one service'),
  description: z.string().optional(),
  budget: z.string().optional(),
  timeline: z.string().optional(),
  priority: z.string().default('MEDIUM'),
});

type LeadFormData = z.infer<typeof leadSchema>;

// Main service categories matching the landing pages
const SERVICES = [
  'Roofing Solutions',
  'Gutter & Rainwater Solutions',
  'Solar Panel Solutions',
  'Pool Solutions',
  'Irrigation Solutions',
  'Paving Solutions',
  'Fencing & Wall Solutions',
  'Renovations',
  'Emergency Services',
  'Other',
];

const LEAD_SOURCES = [
  { value: 'WEB', label: 'Website' },
  { value: 'REFERRAL', label: 'Referral' },
  { value: 'PARTNER', label: 'Partner' },
  { value: 'COLD_CALL', label: 'Cold Call' },
  { value: 'EMAIL', label: 'Email' },
  { value: 'SOCIAL_MEDIA', label: 'Social Media' },
  { value: 'ADVERTISEMENT', label: 'Advertisement' },
  { value: 'OTHER', label: 'Other' },
];

const PRIORITIES = [
  { value: 'LOW', label: 'Low' },
  { value: 'MEDIUM', label: 'Medium' },
  { value: 'HIGH', label: 'High' },
  { value: 'URGENT', label: 'Urgent' },
];

export function NewLeadForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [selectedServices, setSelectedServices] = useState<string[]>([]);
  const [isPrePopulated, setIsPrePopulated] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors },
    setValue,
    watch,
  } = useForm<LeadFormData>({
    resolver: zodResolver(leadSchema),
    defaultValues: {
      priority: 'HIGH', // High priority for landing page submissions
      services: [],
    },
  });

  // Auto-populate form from URL parameters
  useEffect(() => {
    const name = searchParams.get('name');
    const email = searchParams.get('email');
    const phone = searchParams.get('phone');
    const serviceType = searchParams.get('serviceType');
    const address = searchParams.get('address');
    const latitude = searchParams.get('latitude');
    const longitude = searchParams.get('longitude');
    const source = searchParams.get('source');

    if (name || email || phone) {
      setIsPrePopulated(true);
      
      // Parse name into first and last name
      if (name) {
        const nameParts = name.split(' ');
        const firstName = nameParts[0] || '';
        const lastName = nameParts.slice(1).join(' ') || '';
        setValue('firstName', firstName);
        setValue('lastName', lastName);
      }

      if (email) setValue('email', email);
      if (phone) setValue('phone', phone);
      if (address) setValue('address', address);
      if (source) setValue('source', source);
      else setValue('source', 'WEB');

      // Set priority to HIGH for landing page submissions
      setValue('priority', 'HIGH');

      // Set default location info if not provided
      setValue('city', 'Johannesburg');
      setValue('state', 'Gauteng');
      setValue('zipCode', '2000');

      // Set service type
      if (serviceType) {
        setSelectedServices([serviceType]);
        setValue('services', [serviceType]);
      }

      // Add note about GPS location if available
      if (latitude && longitude) {
        const gpsNote = `\n\nGPS Coordinates: ${latitude}, ${longitude}\nView on map: https://www.google.com/maps?q=${latitude},${longitude}`;
        setValue('description', `Landing page submission.${gpsNote}`);
      } else {
        setValue('description', 'Landing page submission.');
      }

      toast.success('Lead pre-populated from landing page submission', {
        description: 'Please review and complete the remaining fields.',
      });
    }
  }, [searchParams, setValue]);

  const source = watch('source');
  const priority = watch('priority');

  const onSubmit = async (data: LeadFormData) => {
    setIsSubmitting(true);

    try {
      const response = await fetch('/api/leads', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...data,
          services: selectedServices,
        }),
      });

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

      const lead = await response.json();

      toast.success('Lead created successfully!', {
        description: `${lead.firstName} ${lead.lastName} has been added to your pipeline.`,
      });

      router.push('/leads');
      router.refresh();
    } catch (error) {
      console.error('Error creating lead:', error);
      toast.error('Failed to create lead', {
        description: 'Please try again or contact support.',
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleServiceToggle = (service: string) => {
    const updated = selectedServices.includes(service)
      ? selectedServices.filter((s) => s !== service)
      : [...selectedServices, service];
    
    setSelectedServices(updated);
    setValue('services', updated);
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4 }}
    >
      {isPrePopulated && (
        <Alert className="mb-6 border-brand-green bg-brand-green/10">
          <InfoIcon className="h-4 w-4 text-brand-green" />
          <AlertDescription className="text-brand-dark-blue">
            This lead was pre-populated from a landing page submission. Please review all fields and add any missing information.
          </AlertDescription>
        </Alert>
      )}

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
        {/* Contact Information */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <User className="w-5 h-5" />
              <span>Contact Information</span>
            </CardTitle>
            <CardDescription>Enter the lead's personal details</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="firstName">First Name *</Label>
                <Input
                  id="firstName"
                  {...register('firstName')}
                  placeholder="John"
                />
                {errors.firstName && (
                  <p className="text-sm text-red-500">{errors.firstName.message}</p>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="lastName">Last Name *</Label>
                <Input
                  id="lastName"
                  {...register('lastName')}
                  placeholder="Smith"
                />
                {errors.lastName && (
                  <p className="text-sm text-red-500">{errors.lastName.message}</p>
                )}
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="email" className="flex items-center space-x-1">
                  <Mail className="w-4 h-4" />
                  <span>Email *</span>
                </Label>
                <Input
                  id="email"
                  type="email"
                  {...register('email')}
                  placeholder="john@example.com"
                />
                {errors.email && (
                  <p className="text-sm text-red-500">{errors.email.message}</p>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="phone" className="flex items-center space-x-1">
                  <Phone className="w-4 h-4" />
                  <span>Phone *</span>
                </Label>
                <Input
                  id="phone"
                  type="tel"
                  {...register('phone')}
                  placeholder="+27 12 345 6789"
                />
                {errors.phone && (
                  <p className="text-sm text-red-500">{errors.phone.message}</p>
                )}
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Address Information */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <MapPin className="w-5 h-5" />
              <span>Address Information</span>
            </CardTitle>
            <CardDescription>Where is the project located?</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="address">Street Address *</Label>
              <Input
                id="address"
                {...register('address')}
                placeholder="123 Main Street"
              />
              {errors.address && (
                <p className="text-sm text-red-500">{errors.address.message}</p>
              )}
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="city">City *</Label>
                <Input
                  id="city"
                  {...register('city')}
                  placeholder="Johannesburg"
                />
                {errors.city && (
                  <p className="text-sm text-red-500">{errors.city.message}</p>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="state">Province/State *</Label>
                <Input
                  id="state"
                  {...register('state')}
                  placeholder="Gauteng"
                />
                {errors.state && (
                  <p className="text-sm text-red-500">{errors.state.message}</p>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="zipCode">Postal Code *</Label>
                <Input
                  id="zipCode"
                  {...register('zipCode')}
                  placeholder="2000"
                />
                {errors.zipCode && (
                  <p className="text-sm text-red-500">{errors.zipCode.message}</p>
                )}
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Services Requested */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <Tag className="w-5 h-5" />
              <span>Services Requested</span>
            </CardTitle>
            <CardDescription>Select all service categories the customer is interested in. Each category includes multiple specialized services.</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
              {SERVICES.map((service) => (
                <div key={service} className="flex items-center space-x-2">
                  <Checkbox
                    id={service}
                    checked={selectedServices.includes(service)}
                    onCheckedChange={() => handleServiceToggle(service)}
                  />
                  <Label htmlFor={service} className="cursor-pointer text-sm font-medium">
                    {service}
                  </Label>
                </div>
              ))}
            </div>
            {errors.services && (
              <p className="text-sm text-red-500 mt-2">{errors.services.message}</p>
            )}
          </CardContent>
        </Card>

        {/* Lead Details */}
        <Card>
          <CardHeader>
            <CardTitle>Lead Details</CardTitle>
            <CardDescription>Additional information about the lead</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="source">Lead Source *</Label>
                <Select value={source} onValueChange={(value) => setValue('source', value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="Select source" />
                  </SelectTrigger>
                  <SelectContent>
                    {LEAD_SOURCES.map((sourceOption) => (
                      <SelectItem key={sourceOption.value} value={sourceOption.value}>
                        {sourceOption.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {errors.source && (
                  <p className="text-sm text-red-500">{errors.source.message}</p>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="priority">Priority</Label>
                <Select value={priority} onValueChange={(value) => setValue('priority', value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="Select priority" />
                  </SelectTrigger>
                  <SelectContent>
                    {PRIORITIES.map((priorityOption) => (
                      <SelectItem key={priorityOption.value} value={priorityOption.value}>
                        {priorityOption.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="budget" className="flex items-center space-x-1">
                  <DollarSign className="w-4 h-4" />
                  <span>Budget (Optional)</span>
                </Label>
                <Input
                  id="budget"
                  {...register('budget')}
                  placeholder="R 50,000"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="timeline" className="flex items-center space-x-1">
                  <Calendar className="w-4 h-4" />
                  <span>Timeline (Optional)</span>
                </Label>
                <Input
                  id="timeline"
                  {...register('timeline')}
                  placeholder="Within 2 weeks"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="description">Description / Notes</Label>
              <Textarea
                id="description"
                {...register('description')}
                placeholder="Additional details about the project..."
                rows={4}
              />
            </div>
          </CardContent>
        </Card>

        {/* Submit Button */}
        <div className="flex justify-end space-x-4">
          <Button
            type="button"
            variant="outline"
            onClick={() => router.back()}
            disabled={isSubmitting}
          >
            Cancel
          </Button>
          <Button type="submit" disabled={isSubmitting}>
            {isSubmitting ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Creating Lead...
              </>
            ) : (
              <>
                <CheckCircle className="mr-2 h-4 w-4" />
                Create Lead
              </>
            )}
          </Button>
        </div>
      </form>
    </motion.div>
  );
}
