import { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Upload, X, DollarSign } from 'lucide-react';
import { Input } from '../components/ui/Input';
import { GradientButton } from '../components/ui/GradientButton';
import { Card } from '../components/ui/Card';
import { LocationInput } from '../components/ui/LocationInput';
import { CATEGORIES, CONDITIONS } from '../utils/constants';
import { api } from '../api/client';

export function SellItemPage() {
  const navigate = useNavigate();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [price, setPrice] = useState('');
  const [category, setCategory] = useState('');
  const [condition, setCondition] = useState('');
  const [location, setLocation] = useState('');
  const [obo, setObo] = useState(false);
  const [photos, setPhotos] = useState<File[]>([]);
  const [previews, setPreviews] = useState<string[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');

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

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    const remaining = 6 - 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 handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setSubmitting(true);

    try {
      // 1. Create the listing
      const listing = await api.post<{ id: string }>('/listings', {
        title,
        description,
        price: parseFloat(price),
        category,
        condition,
        location,
        obo,
      });

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

      // 3. Activate the listing
      await api.post(`/listings/${listing.id}/activate`);

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

  return (
    <div className="max-w-3xl mx-auto px-4 sm:px-6 py-8">
      <Card padding="lg">
        <h1 className="text-2xl font-bold text-gray-900 mb-2">Sell Your Item</h1>
        <p className="text-sm text-gray-500 mb-8">Help buyers find your item with a good description</p>

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

        <form onSubmit={handleSubmit} className="space-y-8">
          {/* Photos */}
          <div>
            <h2 className="text-sm font-semibold text-gray-900 mb-3">Photos</h2>
            <p className="text-xs text-gray-500 mb-3">Add up to 6 photos. First photo will be shown in search results.</p>
            <input ref={fileInputRef} type="file" accept="image/*" multiple className="hidden" onChange={handleFileChange} />
            <div className="grid grid-cols-3 sm:grid-cols-6 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>
                </div>
              ))}
              {photos.length < 6 && (
                <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>

          {/* Details */}
          <div className="space-y-4">
            <h2 className="text-sm font-semibold text-gray-900">Details</h2>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1.5">Category</label>
              <select value={category} onChange={(e) => setCategory(e.target.value)} required
                className="w-full rounded-xl border border-gray-200 bg-white px-4 py-2.5 text-sm text-gray-900 focus:border-primary-400 focus:ring-2 focus:ring-primary-100 focus:outline-none">
                <option value="">Select a category</option>
                {CATEGORIES.map(c => <option key={c.value} value={c.value}>{c.label}</option>)}
              </select>
            </div>
            <Input label="Title" placeholder="What are you selling?" value={title} onChange={(e) => setTitle(e.target.value)} required />
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1.5">Condition</label>
              <select value={condition} onChange={(e) => setCondition(e.target.value)} required
                className="w-full rounded-xl border border-gray-200 bg-white px-4 py-2.5 text-sm text-gray-900 focus:border-primary-400 focus:ring-2 focus:ring-primary-100 focus:outline-none">
                <option value="">Select condition</option>
                {CONDITIONS.map(c => <option key={c.value} value={c.value}>{c.label}</option>)}
              </select>
            </div>
            <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 item 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>
          </div>

          {/* Price */}
          <div className="space-y-4">
            <h2 className="text-sm font-semibold text-gray-900">Price</h2>
            <Input label="Price" type="number" placeholder="0.00" value={price} onChange={(e) => setPrice(e.target.value)} required
              icon={<DollarSign className="w-4 h-4" />} />
            <label className="flex items-center gap-2 text-sm text-gray-700">
              <input type="checkbox" checked={obo} onChange={(e) => setObo(e.target.checked)} className="accent-primary-600" />
              Or Best Offer (OBO)
            </label>
          </div>

          {/* Location */}
          <div>
            <h2 className="text-sm font-semibold text-gray-900 mb-3">Location</h2>
            <LocationInput placeholder="E.g. city, state, zip code" value={location} onChange={setLocation} required />
          </div>

          <GradientButton type="submit" className="w-full" size="lg" disabled={submitting}>
            {submitting ? 'Submitting...' : 'Submit Listing'}
          </GradientButton>
        </form>
      </Card>
    </div>
  );
}
