import { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Upload, X, ChevronRight, ChevronLeft, Check } from 'lucide-react';
import { Card } from '../components/ui/Card';
import { Input } from '../components/ui/Input';
import { GradientButton } from '../components/ui/GradientButton';
import { Button } from '../components/ui/Button';
import { api } from '../api/client';
import type { RentalCategory, CancellationPolicy } from '../types/rental';

const RENTAL_CATEGORIES: { value: RentalCategory; label: string; icon: string }[] = [
  { value: 'APARTMENT', label: 'Apartment', icon: '\uD83C\uDFE2' },
  { value: 'HOUSE', label: 'House', icon: '\uD83C\uDFE0' },
  { value: 'CAR', label: 'Car', icon: '\uD83D\uDE97' },
  { value: 'MOTORCYCLE', label: 'Motorcycle', icon: '\uD83C\uDFCD\uFE0F' },
  { value: 'BICYCLE', label: 'Bicycle', icon: '\uD83D\uDEB2' },
  { value: 'EBIKE', label: 'E-Bike', icon: '\u26A1' },
];

const CANCELLATION_POLICIES: { value: CancellationPolicy; label: string; description: string }[] = [
  { value: 'FLEXIBLE', label: 'Flexible', description: 'Free cancellation up to 24 hours before start' },
  { value: 'MODERATE', label: 'Moderate', description: 'Free cancellation up to 5 days before start' },
  { value: 'STRICT', label: 'Strict', description: 'No refund after booking confirmation' },
];

const STEPS = ['Category', 'Details', 'Pricing', 'Photos'];

export function CreateRentalPage() {
  const navigate = useNavigate();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [step, setStep] = useState(0);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');

  // Step 1: Category
  const [category, setCategory] = useState<RentalCategory | ''>('');

  // Step 2: Details
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [location, setLocation] = useState('');
  const [amenities, setAmenities] = useState('');
  const [rules, setRules] = useState('');

  // Step 3: Pricing
  const [dailyPrice, setDailyPrice] = useState('');
  const [monthlyPrice, setMonthlyPrice] = useState('');
  const [depositAmount, setDepositAmount] = useState('');
  const [cancellationPolicy, setCancellationPolicy] = useState<CancellationPolicy>('FLEXIBLE');
  const [minDays, setMinDays] = useState('');
  const [maxDays, setMaxDays] = useState('');
  const [minMonths, setMinMonths] = useState('');
  const [maxMonths, setMaxMonths] = useState('');

  // Step 4: Photos
  const [photos, setPhotos] = useState<File[]>([]);
  const [previews, setPreviews] = useState<string[]>([]);

  const handleAddPhoto = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    const remaining = 10 - photos.length;
    const newFiles = files.slice(0, remaining);
    if (newFiles.length === 0) return;

    setPhotos(prev => [...prev, ...newFiles]);
    setPreviews(prev => [...prev, ...newFiles.map(f => URL.createObjectURL(f))]);
    e.target.value = '';
  };

  const handleRemovePhoto = (index: number) => {
    URL.revokeObjectURL(previews[index]);
    setPhotos(photos.filter((_, i) => i !== index));
    setPreviews(previews.filter((_, i) => i !== index));
  };

  const canAdvance = () => {
    switch (step) {
      case 0: return !!category;
      case 1: return !!(title && description && location);
      case 2: return !!(dailyPrice || monthlyPrice);
      case 3: return true;
      default: return false;
    }
  };

  const handleSubmit = async () => {
    setError('');
    setSubmitting(true);

    try {
      const amenitiesList = amenities.split('\n').map(s => s.trim()).filter(Boolean);
      const rulesList = rules.split('\n').map(s => s.trim()).filter(Boolean);

      const rental = await api.post<{ id: string }>('/rentals', {
        category,
        title,
        description,
        location,
        amenities: amenitiesList,
        rules: rulesList,
        dailyPrice: dailyPrice ? parseFloat(dailyPrice) : undefined,
        monthlyPrice: monthlyPrice ? parseFloat(monthlyPrice) : undefined,
        depositAmount: depositAmount ? parseFloat(depositAmount) : undefined,
        cancellationPolicy,
        minDays: minDays ? parseInt(minDays) : undefined,
        maxDays: maxDays ? parseInt(maxDays) : undefined,
        minMonths: minMonths ? parseInt(minMonths) : undefined,
        maxMonths: maxMonths ? parseInt(maxMonths) : undefined,
      });

      if (photos.length > 0) {
        const formData = new FormData();
        photos.forEach(file => formData.append('images', file));
        await api.upload(`/rentals/${rental.id}/images`, formData);
      }

      navigate(`/rentals/${rental.id}`);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create rental');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="max-w-3xl mx-auto px-4 sm:px-6 py-8">
      {/* Step indicator */}
      <div className="flex items-center justify-center gap-2 mb-8">
        {STEPS.map((label, i) => (
          <div key={label} className="flex items-center gap-2">
            <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors ${
              i < step ? 'bg-primary-600 text-white' : i === step ? 'bg-primary-100 text-primary-700 ring-2 ring-primary-400' : 'bg-gray-100 text-gray-400'
            }`}>
              {i < step ? <Check className="w-4 h-4" /> : i + 1}
            </div>
            <span className={`hidden sm:block text-sm ${i === step ? 'font-medium text-gray-900' : 'text-gray-400'}`}>{label}</span>
            {i < STEPS.length - 1 && <div className="w-8 h-px bg-gray-200" />}
          </div>
        ))}
      </div>

      <Card padding="lg">
        {error && (
          <div className="mb-6 p-3 bg-red-50 border border-red-200 rounded-xl text-sm text-red-600">{error}</div>
        )}

        {/* Step 1: Category */}
        {step === 0 && (
          <div>
            <h2 className="text-xl font-bold text-gray-900 mb-2">What are you renting out?</h2>
            <p className="text-sm text-gray-500 mb-6">Select a category that best describes your rental.</p>
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
              {RENTAL_CATEGORIES.map(cat => (
                <button
                  key={cat.value}
                  type="button"
                  onClick={() => setCategory(cat.value)}
                  className={`p-4 rounded-xl border-2 text-center transition-all cursor-pointer ${
                    category === cat.value
                      ? 'border-primary-400 bg-primary-50'
                      : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
                  }`}
                >
                  <span className="text-3xl block mb-2">{cat.icon}</span>
                  <span className="text-sm font-medium text-gray-900">{cat.label}</span>
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Step 2: Details */}
        {step === 1 && (
          <div className="space-y-5">
            <div>
              <h2 className="text-xl font-bold text-gray-900 mb-2">Rental Details</h2>
              <p className="text-sm text-gray-500 mb-6">Provide information about your rental.</p>
            </div>
            <Input label="Title" placeholder="e.g. Cozy 2BR Apartment in Downtown" value={title} onChange={(e) => setTitle(e.target.value)} required />
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1.5">Description</label>
              <textarea
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                rows={4}
                required
                placeholder="Describe your rental in detail..."
                className="w-full rounded-xl border border-gray-200 bg-white px-4 py-2.5 text-sm text-gray-900 placeholder:text-gray-400 focus:border-primary-400 focus:ring-2 focus:ring-primary-100 focus:outline-none resize-none"
              />
            </div>
            <Input label="Location" placeholder="City, State or full address" value={location} onChange={(e) => setLocation(e.target.value)} required />
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1.5">Amenities (one per line)</label>
              <textarea
                value={amenities}
                onChange={(e) => setAmenities(e.target.value)}
                rows={3}
                placeholder={"WiFi\nParking\nAir Conditioning"}
                className="w-full rounded-xl border border-gray-200 bg-white px-4 py-2.5 text-sm text-gray-900 placeholder:text-gray-400 focus:border-primary-400 focus:ring-2 focus:ring-primary-100 focus:outline-none resize-none"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1.5">Rules (one per line)</label>
              <textarea
                value={rules}
                onChange={(e) => setRules(e.target.value)}
                rows={3}
                placeholder={"No smoking\nNo pets\nQuiet hours after 10pm"}
                className="w-full rounded-xl border border-gray-200 bg-white px-4 py-2.5 text-sm text-gray-900 placeholder:text-gray-400 focus:border-primary-400 focus:ring-2 focus:ring-primary-100 focus:outline-none resize-none"
              />
            </div>
          </div>
        )}

        {/* Step 3: Pricing */}
        {step === 2 && (
          <div className="space-y-5">
            <div>
              <h2 className="text-xl font-bold text-gray-900 mb-2">Pricing</h2>
              <p className="text-sm text-gray-500 mb-6">Set your rental prices. Fill in at least one pricing period.</p>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Input label="Daily Price ($)" type="number" placeholder="0.00" value={dailyPrice} onChange={(e) => setDailyPrice(e.target.value)} />
              <Input label="Monthly Price ($)" type="number" placeholder="0.00" value={monthlyPrice} onChange={(e) => setMonthlyPrice(e.target.value)} />
            </div>
            <Input label="Security Deposit ($)" type="number" placeholder="0.00" value={depositAmount} onChange={(e) => setDepositAmount(e.target.value)} />

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1.5">Cancellation Policy</label>
              <div className="space-y-2">
                {CANCELLATION_POLICIES.map(policy => (
                  <button
                    key={policy.value}
                    type="button"
                    onClick={() => setCancellationPolicy(policy.value)}
                    className={`w-full text-left p-3 rounded-xl border-2 transition-all cursor-pointer ${
                      cancellationPolicy === policy.value
                        ? 'border-primary-400 bg-primary-50'
                        : 'border-gray-200 hover:border-gray-300'
                    }`}
                  >
                    <span className="text-sm font-medium text-gray-900">{policy.label}</span>
                    <p className="text-xs text-gray-500 mt-0.5">{policy.description}</p>
                  </button>
                ))}
              </div>
            </div>

            <div>
              <h3 className="text-sm font-medium text-gray-700 mb-3">Booking Duration Limits</h3>
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                <Input label="Min Days" type="number" placeholder="1" value={minDays} onChange={(e) => setMinDays(e.target.value)} />
                <Input label="Max Days" type="number" placeholder="30" value={maxDays} onChange={(e) => setMaxDays(e.target.value)} />
                <Input label="Min Months" type="number" placeholder="1" value={minMonths} onChange={(e) => setMinMonths(e.target.value)} />
                <Input label="Max Months" type="number" placeholder="12" value={maxMonths} onChange={(e) => setMaxMonths(e.target.value)} />
              </div>
            </div>
          </div>
        )}

        {/* Step 4: Photos */}
        {step === 3 && (
          <div>
            <h2 className="text-xl font-bold text-gray-900 mb-2">Photos</h2>
            <p className="text-sm text-gray-500 mb-6">Add up to 10 photos. The first photo will be your cover image.</p>
            <input ref={fileInputRef} type="file" accept="image/*" multiple className="hidden" onChange={handleFileChange} />
            <div className="grid grid-cols-3 sm:grid-cols-5 gap-3">
              {previews.map((src, i) => (
                <div key={i} className="relative aspect-square rounded-xl overflow-hidden">
                  <img src={src} alt="" className="w-full h-full object-cover" />
                  <button
                    type="button"
                    onClick={() => handleRemovePhoto(i)}
                    className="absolute -top-1 -right-1 w-5 h-5 bg-red-500 text-white rounded-full flex items-center justify-center cursor-pointer"
                  >
                    <X className="w-3 h-3" />
                  </button>
                  {i === 0 && (
                    <span className="absolute bottom-1 left-1 text-xs bg-black/60 text-white px-1.5 py-0.5 rounded">Cover</span>
                  )}
                </div>
              ))}
              {photos.length < 10 && (
                <button
                  type="button"
                  onClick={handleAddPhoto}
                  className="aspect-square border-2 border-dashed border-gray-200 rounded-xl flex flex-col items-center justify-center gap-1 hover:border-primary-300 hover:bg-primary-50 transition-colors cursor-pointer"
                >
                  <Upload className="w-5 h-5 text-gray-400" />
                  <span className="text-xs text-gray-400">Add</span>
                </button>
              )}
            </div>
          </div>
        )}

        {/* Navigation buttons */}
        <div className="flex justify-between mt-8">
          {step > 0 ? (
            <Button variant="secondary" onClick={() => setStep(step - 1)}>
              <ChevronLeft className="w-4 h-4 mr-1" /> Back
            </Button>
          ) : (
            <div />
          )}
          {step < STEPS.length - 1 ? (
            <GradientButton onClick={() => setStep(step + 1)} disabled={!canAdvance()}>
              Next <ChevronRight className="w-4 h-4 ml-1" />
            </GradientButton>
          ) : (
            <GradientButton onClick={handleSubmit} disabled={submitting}>
              {submitting ? 'Creating...' : 'Create Rental'}
            </GradientButton>
          )}
        </div>
      </Card>
    </div>
  );
}
