import { Building2, Globe, Mail, Phone, 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 { Textarea } from '@/components/ui/textarea';
import { useAuth } from '@/contexts/AuthContext';
import { businessesApi } from '@/db/api';
import { useToast } from '@/hooks/use-toast';

const BusinessRegister = () => {
  const { user } = useAuth();
  const navigate = useNavigate();
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    category: '',
    phone: '',
    email: '',
    website: '',
  });

  useEffect(() => {
    if (!user) {
      toast({
        title: 'Giriş Gerekli',
        description: 'İşletme kaydı için giriş yapmalısınız.',
        variant: 'destructive',
      });
      navigate('/');
      return;
    }

    // Kullanıcının zaten işletmesi var mı kontrol et
    checkExistingBusiness();
  }, [user]);

  const checkExistingBusiness = async () => {
    try {
      const business = await businessesApi.getUserBusiness();
      if (business) {
        navigate('/business/dashboard');
      }
    } catch (error) {
      console.error('İşletme kontrolü hatası:', error);
    }
  };

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

    try {
      setLoading(true);
      await businessesApi.create(formData);
      toast({
        title: 'Başarılı',
        description: 'İşletmeniz başarıyla kaydedildi.',
      });
      navigate('/business/dashboard');
    } catch (error: any) {
      console.error('İşletme kayıt hatası:', error);
      toast({
        title: 'Hata',
        description: error.message || 'İşletme kaydedilemedi.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <div className="min-h-screen bg-gradient-to-br from-primary/5 to-accent/5 py-12">
      <div className="container mx-auto px-4 max-w-2xl">
        <div className="text-center mb-8">
          <Building2 className="h-16 w-16 mx-auto mb-4 text-primary" />
          <h1 className="text-4xl font-bold mb-2">İşletmenizi Kaydedin</h1>
          <p className="text-muted-foreground">
            LetsGoCappadocia'ya katılın ve işletmenizi Kapadokya'yı ziyaret eden gezginlere tanıtın
          </p>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>İşletme Bilgileri</CardTitle>
            <CardDescription>
              İşletmeniz hakkında temel bilgileri girin
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-6">
              <div className="space-y-2">
                <Label htmlFor="name">İşletme Adı *</Label>
                <Input
                  id="name"
                  name="name"
                  placeholder="Örn: Kapadokya Otel"
                  value={formData.name}
                  onChange={handleChange}
                  required
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="category">Kategori</Label>
                <Input
                  id="category"
                  name="category"
                  placeholder="Örn: Otel, Restoran, Müze"
                  value={formData.category}
                  onChange={handleChange}
                />
              </div>

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

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="email">E-posta *</Label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="email"
                      name="email"
                      type="email"
                      placeholder="info@isletme.com"
                      value={formData.email}
                      onChange={handleChange}
                      className="pl-10"
                      required
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="phone">Telefon *</Label>
                  <div className="relative">
                    <Phone className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="phone"
                      name="phone"
                      type="tel"
                      placeholder="+90 555 123 4567"
                      value={formData.phone}
                      onChange={handleChange}
                      className="pl-10"
                      required
                    />
                  </div>
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="website">Website</Label>
                <div className="relative">
                  <Globe className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                  <Input
                    id="website"
                    name="website"
                    type="url"
                    placeholder="https://www.isletme.com"
                    value={formData.website}
                    onChange={handleChange}
                    className="pl-10"
                  />
                </div>
              </div>

              <div className="flex gap-4 pt-4">
                <Button
                  type="button"
                  variant="outline"
                  className="flex-1"
                  onClick={() => navigate('/')}
                >
                  İptal
                </Button>
                <Button
                  type="submit"
                  className="flex-1"
                  disabled={loading}
                >
                  {loading ? 'Kaydediliyor...' : 'İşletmeyi Kaydet'}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>

        <div className="mt-8 text-center text-sm text-muted-foreground">
          <p>İşletmenizi kaydederek <a href="#" className="text-primary hover:underline">Kullanım Koşullarını</a> kabul etmiş olursunuz.</p>
        </div>
      </div>
    </div>
  );
};

export default BusinessRegister;
