import React, { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Calendar,
  Mail,
  Lock,
  Clock,
  ArrowLeft,
  Info
} from 'lucide-react';
import { format, addDays } from 'date-fns';
import { toast } from 'react-toastify';

import { Button, Input, Card } from '../../components/common';
import { useMutation } from '@tanstack/react-query';
import { eventsService } from '../../services/events.service';

interface FormData {
  event_type: string;
  event_name: string;
  event_date: string;
  host_email: string;
  admin_email: string;
  password: string;
  confirm_password: string;
  welcome_message: string;
  color_theme: string;
  expires_in_days: number;
}

const EVENT_TYPES = [
  { value: 'wedding', label: 'Wedding', emoji: '💒' },
  { value: 'birthday', label: 'Birthday', emoji: '🎂' },
  { value: 'corporate', label: 'Corporate', emoji: '🏢' },
  { value: 'other', label: 'Other', emoji: '📸' },
];

const COLOR_THEMES = [
  { 
    value: 'default', 
    label: 'Default (Green)', 
    color: 'bg-primary-600',
    theme: {
      primaryColor: '#5C8762',
      accentColor: '#22c55e',
      backgroundColor: '#fafafa',
      textColor: '#171717',
      borderRadius: 'md' as const
    }
  },
  { 
    value: 'blue', 
    label: 'Ocean Blue', 
    color: 'bg-blue-600',
    theme: {
      primaryColor: '#2563eb',
      accentColor: '#3b82f6',
      backgroundColor: '#f0f9ff',
      textColor: '#0f172a',
      borderRadius: 'md' as const
    }
  },
  { 
    value: 'purple', 
    label: 'Royal Purple', 
    color: 'bg-purple-600',
    theme: {
      primaryColor: '#9333ea',
      accentColor: '#a855f7',
      backgroundColor: '#faf5ff',
      textColor: '#1e1b4b',
      borderRadius: 'md' as const
    }
  },
  { 
    value: 'rose', 
    label: 'Rose Gold', 
    color: 'bg-rose-600',
    theme: {
      primaryColor: '#e11d48',
      accentColor: '#f43f5e',
      backgroundColor: '#fff1f2',
      textColor: '#881337',
      borderRadius: 'md' as const
    }
  },
  { 
    value: 'amber', 
    label: 'Sunset Amber', 
    color: 'bg-amber-600',
    theme: {
      primaryColor: '#d97706',
      accentColor: '#f59e0b',
      backgroundColor: '#fffbeb',
      textColor: '#451a03',
      borderRadius: 'md' as const
    }
  },
];

export const CreateEventPage: React.FC = () => {
  const navigate = useNavigate();
  const isMountedRef = useRef(true);
  
  useEffect(() => {
    return () => {
      isMountedRef.current = false;
    };
  }, []);
  
  const [formData, setFormData] = useState<FormData>({
    event_type: 'wedding',
    event_name: '',
    event_date: format(new Date(), 'yyyy-MM-dd'),
    host_email: '',
    admin_email: '',
    password: '',
    confirm_password: '',
    welcome_message: '',
    color_theme: 'default',
    expires_in_days: 30,
  });
  
  const [errors, setErrors] = useState<Partial<Record<keyof FormData, string>>>({});
  const [showPassword, setShowPassword] = useState(false);

  const createMutation = useMutation({
    mutationFn: eventsService.createEvent,
    onSuccess: (data) => {
      if (isMountedRef.current) {
        toast.success('Event created successfully!');
        // Add a small delay to ensure navigation works properly
        setTimeout(() => {
          if (isMountedRef.current && data?.id) {
            navigate(`/admin/events/${data.id}`);
          } else {
            navigate('/admin/events');
          }
        }, 100);
      }
    },
    onError: (error: any) => {
      if (!isMountedRef.current) return;
      
      if (error.code === 'ERR_NETWORK' || error.code === 'ERR_CONNECTION_RESET') {
        toast.error('Network error. Please check your connection and try again.');
      } else if (error.response?.data?.errors) {
        const newErrors: Record<string, string> = {};
        error.response.data.errors.forEach((err: any) => {
          newErrors[err.path] = err.msg;
        });
        setErrors(newErrors);
      } else if (error.response?.status === 401) {
        toast.error('Session expired. Please login again.');
        navigate('/admin/login');
      } else {
        toast.error(error.response?.data?.error || 'Failed to create event');
      }
    },
  });

  const validateForm = (): boolean => {
    const newErrors: Partial<Record<keyof FormData, string>> = {};

    if (!formData.event_name.trim()) {
      newErrors.event_name = 'Event name is required';
    }

    if (!formData.host_email) {
      newErrors.host_email = 'Host email is required';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.host_email)) {
      newErrors.host_email = 'Invalid email format';
    }

    if (!formData.admin_email) {
      newErrors.admin_email = 'Admin email is required';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.admin_email)) {
      newErrors.admin_email = 'Invalid email format';
    }

    if (!formData.password) {
      newErrors.password = 'Password is required';
    } else if (formData.password.length < 6) {
      newErrors.password = 'Password must be at least 6 characters';
    }

    if (formData.password !== formData.confirm_password) {
      newErrors.confirm_password = 'Passwords do not match';
    }

    if (formData.expires_in_days < 1 || formData.expires_in_days > 365) {
      newErrors.expires_in_days = 'Expiration must be between 1 and 365 days';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }

    const selectedTheme = COLOR_THEMES.find(t => t.value === formData.color_theme);
    
    createMutation.mutate({
      event_type: formData.event_type,
      event_name: formData.event_name,
      event_date: formData.event_date,
      host_email: formData.host_email,
      admin_email: formData.admin_email,
      password: formData.password,
      welcome_message: formData.welcome_message || '',
      color_theme: selectedTheme ? JSON.stringify(selectedTheme.theme) : undefined,
      expiration_days: formData.expires_in_days,
    });
  };

  const handleInputChange = (field: keyof FormData) => (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  ) => {
    const value = field === 'expires_in_days' ? parseInt(e.target.value) || 0 : e.target.value;
    setFormData(prev => ({ ...prev, [field]: value }));
    
    // Clear error when user types
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: '' }));
    }
  };

  return (
    <div className="max-w-4xl mx-auto">
      {/* Page Header */}
      <div className="mb-6">
        <Button
          variant="outline"
          size="sm"
          leftIcon={<ArrowLeft className="w-4 h-4" />}
          onClick={() => navigate('/admin/events')}
          className="mb-4"
        >
          Back to Events
        </Button>
        
        <h1 className="text-2xl font-bold text-neutral-900">Create New Event</h1>
        <p className="text-neutral-600 mt-1">Set up a new photo gallery for your event</p>
      </div>

      <form onSubmit={handleSubmit}>
        {/* Event Details */}
        <Card padding="md" className="mb-6">
          <h2 className="text-lg font-semibold text-neutral-900 mb-4">Event Details</h2>
          
          <div className="space-y-4">
            {/* Event Type */}
            <div>
              <label className="block text-sm font-medium text-neutral-700 mb-1">
                Event Type
              </label>
              <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
                {EVENT_TYPES.map(type => (
                  <button
                    key={type.value}
                    type="button"
                    onClick={() => setFormData(prev => ({ ...prev, event_type: type.value }))}
                    className={`p-3 rounded-lg border-2 transition-all ${
                      formData.event_type === type.value
                        ? 'border-primary-600 bg-primary-50'
                        : 'border-neutral-200 hover:border-neutral-300'
                    }`}
                  >
                    <div className="text-2xl mb-1">{type.emoji}</div>
                    <div className="text-sm font-medium">{type.label}</div>
                  </button>
                ))}
              </div>
            </div>

            {/* Event Name */}
            <div>
              <label htmlFor="event_name" className="block text-sm font-medium text-neutral-700 mb-1">
                Event Name
              </label>
              <Input
                id="event_name"
                type="text"
                value={formData.event_name}
                onChange={handleInputChange('event_name')}
                error={errors.event_name}
                placeholder="e.g., Smith-Jones Wedding"
                leftIcon={<Calendar className="w-5 h-5 text-neutral-400" />}
              />
            </div>

            {/* Event Date */}
            <div>
              <label htmlFor="event_date" className="block text-sm font-medium text-neutral-700 mb-1">
                Event Date
              </label>
              <Input
                id="event_date"
                type="date"
                value={formData.event_date}
                onChange={handleInputChange('event_date')}
                error={errors.event_date}
              />
            </div>

            {/* Welcome Message */}
            <div>
              <label htmlFor="welcome_message" className="block text-sm font-medium text-neutral-700 mb-1">
                Welcome Message (Optional)
              </label>
              <textarea
                id="welcome_message"
                value={formData.welcome_message}
                onChange={handleInputChange('welcome_message')}
                placeholder="A personalized message for your guests..."
                className="w-full px-3 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                rows={3}
              />
            </div>
          </div>
        </Card>

        {/* Contact Information */}
        <Card padding="md" className="mb-6">
          <h2 className="text-lg font-semibold text-neutral-900 mb-4">Contact Information</h2>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Host Email */}
            <div>
              <label htmlFor="host_email" className="block text-sm font-medium text-neutral-700 mb-1">
                Host Email
              </label>
              <Input
                id="host_email"
                type="email"
                value={formData.host_email}
                onChange={handleInputChange('host_email')}
                error={errors.host_email}
                placeholder="host@example.com"
                leftIcon={<Mail className="w-5 h-5 text-neutral-400" />}
              />
              <p className="text-xs text-neutral-500 mt-1">
                Will receive gallery creation and expiration notifications
              </p>
            </div>

            {/* Admin Email */}
            <div>
              <label htmlFor="admin_email" className="block text-sm font-medium text-neutral-700 mb-1">
                Admin Notification Email
              </label>
              <Input
                id="admin_email"
                type="email"
                value={formData.admin_email}
                onChange={handleInputChange('admin_email')}
                error={errors.admin_email}
                placeholder="admin@example.com"
                leftIcon={<Mail className="w-5 h-5 text-neutral-400" />}
              />
              <p className="text-xs text-neutral-500 mt-1">
                Will receive system notifications and archive confirmations
              </p>
            </div>
          </div>
        </Card>

        {/* Security & Access */}
        <Card padding="md" className="mb-6">
          <h2 className="text-lg font-semibold text-neutral-900 mb-4">Security & Access</h2>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Password */}
            <div>
              <label htmlFor="password" className="block text-sm font-medium text-neutral-700 mb-1">
                Gallery Password
              </label>
              <div className="relative">
                <Input
                  id="password"
                  type={showPassword ? 'text' : 'password'}
                  value={formData.password}
                  onChange={handleInputChange('password')}
                  error={errors.password}
                  placeholder="Enter password"
                  leftIcon={<Lock className="w-5 h-5 text-neutral-400" />}
                />
              </div>
            </div>

            {/* Confirm Password */}
            <div>
              <label htmlFor="confirm_password" className="block text-sm font-medium text-neutral-700 mb-1">
                Confirm Password
              </label>
              <Input
                id="confirm_password"
                type={showPassword ? 'text' : 'password'}
                value={formData.confirm_password}
                onChange={handleInputChange('confirm_password')}
                error={errors.confirm_password}
                placeholder="Confirm password"
                leftIcon={<Lock className="w-5 h-5 text-neutral-400" />}
              />
            </div>
          </div>

          <div className="mt-4">
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={showPassword}
                onChange={(e) => setShowPassword(e.target.checked)}
                className="w-4 h-4 text-primary-600 border-neutral-300 rounded focus:ring-primary-500"
              />
              <span className="ml-2 text-sm text-neutral-700">Show passwords</span>
            </label>
          </div>
        </Card>

        {/* Gallery Settings */}
        <Card padding="md" className="mb-6">
          <h2 className="text-lg font-semibold text-neutral-900 mb-4">Gallery Settings</h2>
          
          <div className="space-y-4">
            {/* Color Theme */}
            <div>
              <label className="block text-sm font-medium text-neutral-700 mb-1">
                Color Theme
              </label>
              <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
                {COLOR_THEMES.map(theme => (
                  <button
                    key={theme.value}
                    type="button"
                    onClick={() => setFormData(prev => ({ ...prev, color_theme: theme.value }))}
                    className={`p-3 rounded-lg border-2 transition-all ${
                      formData.color_theme === theme.value
                        ? 'border-primary-600 ring-2 ring-primary-200'
                        : 'border-neutral-200 hover:border-neutral-300'
                    }`}
                  >
                    <div className={`w-full h-8 ${theme.color} rounded mb-2`} />
                    <div className="text-xs font-medium">{theme.label}</div>
                  </button>
                ))}
              </div>
            </div>

            {/* Expiration */}
            <div>
              <label htmlFor="expires_in_days" className="block text-sm font-medium text-neutral-700 mb-1">
                Gallery Expires In
              </label>
              <div className="flex items-center gap-4">
                <Input
                  id="expires_in_days"
                  type="number"
                  value={formData.expires_in_days}
                  onChange={handleInputChange('expires_in_days')}
                  error={errors.expires_in_days}
                  min="1"
                  max="365"
                  className="w-32"
                  leftIcon={<Clock className="w-5 h-5 text-neutral-400" />}
                />
                <span className="text-sm text-neutral-700">days</span>
              </div>
              <div className="mt-2 p-3 bg-blue-50 rounded-lg flex items-start gap-2">
                <Info className="w-5 h-5 text-blue-600 flex-shrink-0" />
                <div className="text-sm text-blue-800">
                  <p>Gallery will expire on {format(addDays(new Date(), formData.expires_in_days), 'MMMM d, yyyy')}</p>
                  <p className="mt-1">Guests will receive a warning email 7 days before expiration.</p>
                </div>
              </div>
            </div>
          </div>
        </Card>

        {/* Submit Buttons */}
        <div className="flex justify-end gap-3">
          <Button
            type="button"
            variant="outline"
            onClick={() => navigate('/admin/events')}
          >
            Cancel
          </Button>
          <Button
            type="submit"
            variant="primary"
            isLoading={createMutation.isPending}
          >
            Create Event
          </Button>
        </div>
      </form>
    </div>
  );
};

CreateEventPage.displayName = 'CreateEventPage';