import { MapPin, Upload } from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { useAuth } from '@/contexts/AuthContext';
import { businessesApi } from '@/db/api';
import { useToast } from '@/hooks/use-toast';

const AddPlace = () => {
  const { user } = useAuth();
  const navigate = useNavigate();
  const { toast } = useToast();
  const [business, setBusiness] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    type: '',
    city: '',
    country: 'Türkiye',
    image_url: '',
  });

  const placeTypes = [
    'Müze',
    'Restoran',
    'Otel',
    'Park',
    'Plaj',
    'Tarihi Yer',
    'Doğal Oluşum',
    'Aktivite',
    'Kasaba',
  ];

  useEffect(() => {
    if (!user) {
      navigate('/business/register');
      return;
    }
    loadBusiness();
  }, [user]);

  const loadBusiness = async () => {
    try {
      const businessData = await businessesApi.getUserBusiness();
      if (!businessData) {
        navigate('/business/register');
        return;
      }
      setBusiness(businessData);
    } catch (error) {
      console.error('İşletme yükleme hatası:', error);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.name || !formData.city) {
      toast({
        title: 'Eksik Bilgi',
        description: 'Lütfen zorunlu alanları doldurun.',
        variant: 'destructive',
      });
      return;
    }

    if (!business) {
      toast({
        title: 'Hata',
        description: 'İşletme bilgisi bulunamadı.',
        variant: 'destructive',
      });
      return;
    }

    try {
      setLoading(true);
      await businessesApi.addPlace(business.id, formData);
      toast({
        title: 'Başarılı',
        description: 'Yer başarıyla eklendi.',
      });
      navigate('/business/places');
    } catch (error: any) {
      console.error('Yer ekleme hatası:', error);
      toast({
        title: 'Hata',
        description: error.message || 'Yer eklenemedi.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <div className="container mx-auto px-4 py-8 max-w-2xl">
      <div className="mb-8">
        <h1 className="text-3xl font-bold flex items-center gap-3 mb-2">
          <MapPin className="h-8 w-8 text-primary" />
          Yeni Yer Ekle
        </h1>
        <p className="text-muted-foreground">
          İşletmenize ait yeni bir yer ekleyin
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Yer Bilgileri</CardTitle>
          <CardDescription>
            Eklemek istediğiniz yer hakkında bilgileri girin
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="space-y-2">
              <Label htmlFor="name">Yer Adı *</Label>
              <Input
                id="name"
                name="name"
                placeholder="Örn: Sultanahmet Camii"
                value={formData.name}
                onChange={handleChange}
                required
              />
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="type">Kategori</Label>
                <Select
                  value={formData.type}
                  onValueChange={(value) => setFormData(prev => ({ ...prev, type: value }))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Kategori seçin" />
                  </SelectTrigger>
                  <SelectContent>
                    {placeTypes.map(type => (
                      <SelectItem key={type} value={type}>{type}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="city">Şehir *</Label>
                <Input
                  id="city"
                  name="city"
                  placeholder="Örn: İstanbul"
                  value={formData.city}
                  onChange={handleChange}
                  required
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="description">Açıklama</Label>
              <Textarea
                id="description"
                name="description"
                placeholder="Yer hakkında detaylı açıklama yazın..."
                value={formData.description}
                onChange={handleChange}
                rows={4}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="image_url">Görsel URL</Label>
              <Input
                id="image_url"
                name="image_url"
                type="url"
                placeholder="https://example.com/image.jpg"
                value={formData.image_url}
                onChange={handleChange}
              />
              <p className="text-xs text-muted-foreground">
                Yerin fotoğrafının URL'sini girin
              </p>
            </div>

            <div className="flex gap-4 pt-4">
              <Button
                type="button"
                variant="outline"
                className="flex-1"
                onClick={() => navigate('/business/places')}
              >
                İptal
              </Button>
              <Button
                type="submit"
                className="flex-1"
                disabled={loading}
              >
                {loading ? 'Ekleniyor...' : 'Yeri Ekle'}
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
};

export default AddPlace;
