import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { mockApi } from '@/services/mockApi';
import { useAuth } from '@/contexts/AuthContext';
import { ImagePlus, MapPin, DollarSign, Tag } from 'lucide-react';

const AddListing = () => {
  const { user } = useAuth();
  const [isLoading, setIsLoading] = useState(false);
  const [formData, setFormData] = useState({
    title: '',
    category: 'hotel',
    description: '',
    price: '',
    location: '',
    amenities: '',
    image: ''
  });

  const categories = [
    { value: 'hotel', label: 'Hotel' },
    { value: 'restaurant', label: 'Restaurant' },
    { value: 'tour', label: 'Tour Guide' },
    { value: 'shop', label: 'Shop' },
    { value: 'museum', label: 'Museum' },
    { value: 'transport', label: 'Transport' }
  ];

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);

    try {
      const amenitiesArray = formData.amenities.split(',').map(a => a.trim()).filter(a => a);
      
      await mockApi.createListing({
        ...formData,
        price: parseFloat(formData.price),
        amenities: amenitiesArray,
        location: {
          lat: 18.4861 + (Math.random() - 0.5) * 0.01,
          lng: -69.9312 + (Math.random() - 0.5) * 0.01,
          address: formData.location
        },
        ownerId: user?.id
      });

      // Reset form
      setFormData({
        title: '',
        category: 'hotel',
        description: '',
        price: '',
        location: '',
        amenities: '',
        image: ''
      });

      alert('Listing created successfully!');
    } catch (error) {
      console.error('Error creating listing:', error);
      alert('Error creating listing');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-background p-6">
      {/* Page Header */}
      <div className="mb-8">
        <div className="text-center mb-4">
          <div className="text-2xl font-caveat text-primary mb-2">Add New</div>
          <h2 className="text-4xl font-bold text-foreground mb-4">Create Listing</h2>
          <p className="text-muted-foreground">Fill in the information below to create your new listing</p>
        </div>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-4 gap-6 max-w-7xl mx-auto">
        {/* Main Form */}
        <div className="xl:col-span-3">
          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Basic Information Card */}
            <Card className="backdrop-blur-sm bg-card/50 border-border">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Tag size={20} />
                  Basic Information
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="text-sm font-medium text-foreground mb-2 block">
                      Listing Title <span className="text-destructive">*</span>
                    </label>
                    <Input
                      type="text"
                      name="title"
                      value={formData.title}
                      onChange={handleChange}
                      placeholder="Enter listing title"
                      required
                    />
                  </div>
                  
                  <div>
                    <label className="text-sm font-medium text-foreground mb-2 block">
                      Category <span className="text-destructive">*</span>
                    </label>
                    <select
                      name="category"
                      value={formData.category}
                      onChange={handleChange}
                      className="w-full p-2 border border-border rounded-md bg-background text-foreground"
                      required
                    >
                      {categories.map((cat) => (
                        <option key={cat.value} value={cat.value}>
                          {cat.label}
                        </option>
                      ))}
                    </select>
                  </div>
                </div>
                
                <div>
                  <label className="text-sm font-medium text-foreground mb-2 block">
                    Description <span className="text-destructive">*</span>
                  </label>
                  <textarea
                    name="description"
                    value={formData.description}
                    onChange={handleChange}
                    placeholder="Describe your listing in detail..."
                    rows={4}
                    className="w-full p-2 border border-border rounded-md bg-background text-foreground resize-none"
                    required
                  />
                </div>
              </CardContent>
            </Card>

            {/* Location & Pricing Card */}
            <Card className="backdrop-blur-sm bg-card/50 border-border">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <MapPin size={20} />
                  Location & Pricing
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="text-sm font-medium text-foreground mb-2 block">
                      Location <span className="text-destructive">*</span>
                    </label>
                    <Input
                      type="text"
                      name="location"
                      value={formData.location}
                      onChange={handleChange}
                      placeholder="Enter full address"
                      required
                    />
                  </div>
                  
                  <div>
                    <label className="text-sm font-medium text-foreground mb-2 block">
                      <DollarSign className="inline mr-1" size={16} />
                      Price (USD) <span className="text-destructive">*</span>
                    </label>
                    <Input
                      type="number"
                      name="price"
                      value={formData.price}
                      onChange={handleChange}
                      placeholder="0.00"
                      step="0.01"
                      min="0"
                      required
                    />
                  </div>
                </div>
                
                <div>
                  <label className="text-sm font-medium text-foreground mb-2 block">
                    Amenities & Features
                  </label>
                  <Input
                    type="text"
                    name="amenities"
                    value={formData.amenities}
                    onChange={handleChange}
                    placeholder="WiFi, Parking, Pool, Restaurant, Air Conditioning..."
                  />
                  <p className="text-xs text-muted-foreground mt-1">Separate multiple amenities with commas</p>
                </div>
              </CardContent>
            </Card>

            {/* Image Upload Card */}
            <Card className="backdrop-blur-sm bg-card/50 border-border">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <ImagePlus size={20} />
                  Images
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="border-2 border-dashed border-primary rounded-lg p-8 text-center bg-primary/5">
                  <ImagePlus size={48} className="mx-auto text-muted-foreground mb-3" />
                  <h6 className="mb-2 font-medium">Upload Images</h6>
                  <p className="text-muted-foreground mb-3">Drag & drop images here or paste URL below</p>
                  <Input
                    type="url"
                    name="image"
                    value={formData.image}
                    onChange={handleChange}
                    placeholder="Paste image URL here"
                    className="max-w-md mx-auto"
                  />
                </div>
              </CardContent>
            </Card>

            {/* Action Buttons */}
            <div className="flex justify-end gap-3">
              <Button
                type="button"
                variant="outline"
                onClick={() => window.history.back()}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={isLoading}
                className="bg-primary text-primary-foreground hover:bg-primary/90"
              >
                {isLoading ? (
                  <>
                    <span className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></span>
                    Creating...
                  </>
                ) : (
                  <>
                    Create Listing
                  </>
                )}
              </Button>
            </div>
          </form>
        </div>

        {/* Sidebar */}
        <div className="xl:col-span-1 space-y-6">
          <Card className="backdrop-blur-sm bg-card/50 border-border">
            <CardHeader>
              <CardTitle>Publishing Tips</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-start gap-3">
                <div className="bg-primary rounded-full p-2 flex items-center justify-center min-w-[32px] h-8">
                  <ImagePlus size={14} className="text-white" />
                </div>
                <div>
                  <h6 className="font-medium mb-1">High-Quality Images</h6>
                  <p className="text-sm text-muted-foreground">Upload clear, high-resolution images to attract more customers</p>
                </div>
              </div>
              
              <div className="flex items-start gap-3">
                <div className="bg-primary rounded-full p-2 flex items-center justify-center min-w-[32px] h-8">
                  <Tag size={14} className="text-white" />
                </div>
                <div>
                  <h6 className="font-medium mb-1">Detailed Description</h6>
                  <p className="text-sm text-muted-foreground">Provide comprehensive details about your services and amenities</p>
                </div>
              </div>
              
              <div className="flex items-start gap-3">
                <div className="bg-primary rounded-full p-2 flex items-center justify-center min-w-[32px] h-8">
                  <MapPin size={14} className="text-white" />
                </div>
                <div>
                  <h6 className="font-medium mb-1">Accurate Location</h6>
                  <p className="text-sm text-muted-foreground">Include precise address for better discoverability</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="backdrop-blur-sm bg-card/50 border-border">
            <CardContent className="p-6 text-center">
              <img 
                src="https://img.freepik.com/foto-gratis/vista-superior-mano-sosteniendo-telefono-inteligente_23-2149617681.jpg" 
                alt="Mobile app" 
                className="w-full h-48 object-cover rounded-lg mb-3"
              />
              <h6 className="font-medium mb-2">Need Help?</h6>
              <p className="text-sm text-muted-foreground mb-3">Contact our support team for assistance with your listing</p>
              <Button variant="outline" size="sm">
                Get Support
              </Button>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
};

export default AddListing;