import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Building2, MapPin, Tag } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import { supabase } from '@/db/supabase';
import { useAuth } from '@/contexts/AuthContext';

interface ProviderRegistrationModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}

export function ProviderRegistrationModal({ isOpen, onClose, onSuccess }: ProviderRegistrationModalProps) {
  const { toast } = useToast();
  const navigate = useNavigate();
  const { profile, refreshProfile } = useAuth();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    businessName: '',
    businessDescription: '',
    destinations: 'Kapadokya',
    activityCategories: '',
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!profile?.id) {
      toast({
        title: 'Hata',
        description: 'Kullanıcı bilgileri bulunamadı',
        variant: 'destructive',
      });
      return;
    }

    if (!formData.businessName.trim()) {
      toast({
        title: 'Hata',
        description: 'İşletme adı zorunludur',
        variant: 'destructive',
      });
      return;
    }

    if (!formData.activityCategories.trim()) {
      toast({
        title: 'Hata',
        description: 'En az bir aktivite kategorisi girmelisiniz',
        variant: 'destructive',
      });
      return;
    }

    setLoading(true);

    try {
      const destinations = formData.destinations
        .split(',')
        .map(d => d.trim())
        .filter(d => d.length > 0);

      const activityCategories = formData.activityCategories
        .split(',')
        .map(a => a.trim())
        .filter(a => a.length > 0);

      console.log('[ProviderRegistration] Calling register_provider with:', {
        p_user_id: profile.id,
        p_business_name: formData.businessName,
        p_business_description: formData.businessDescription,
        p_destinations: destinations,
        p_activity_categories: activityCategories,
      });

      const { data, error } = await (supabase.rpc as any)('register_provider', {
        p_user_id: profile.id,
        p_business_name: formData.businessName,
        p_business_description: formData.businessDescription,
        p_destinations: destinations,
        p_activity_categories: activityCategories,
      });

      if (error) {
        console.error('[ProviderRegistration] Error:', error);
        throw error;
      }

      console.log('[ProviderRegistration] Success:', data);

      toast({
        title: 'Başarılı!',
        description: 'Provider kaydınız tamamlandı. Yönlendiriliyorsunuz...',
      });

      // Refresh profile to get updated role
      await refreshProfile();

      // Close modal
      onClose();

      // Call success callback if provided
      if (onSuccess) {
        onSuccess();
      }

      // Navigate to provider dashboard
      setTimeout(() => {
        navigate('/provider/dashboard');
      }, 1000);

    } catch (error: any) {
      console.error('[ProviderRegistration] Error:', error);
      toast({
        title: 'Hata',
        description: error.message || 'Provider kaydı sırasında bir hata oluştu',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Provider Kaydı</DialogTitle>
          <DialogDescription>
            İşletme bilgilerinizi girerek provider olarak kayıt olun
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="businessName" className="flex items-center gap-2">
                <Building2 className="h-4 w-4" />
                İşletme Adı *
              </Label>
              <Input
                id="businessName"
                placeholder="Örn: Kapadokya Tur Şirketi"
                value={formData.businessName}
                onChange={(e) => setFormData({ ...formData, businessName: e.target.value })}
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="businessDescription">
                İşletme Açıklaması
              </Label>
              <Textarea
                id="businessDescription"
                placeholder="İşletmeniz hakkında kısa bir açıklama yazın..."
                value={formData.businessDescription}
                onChange={(e) => setFormData({ ...formData, businessDescription: e.target.value })}
                rows={4}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="destinations" className="flex items-center gap-2">
                <MapPin className="h-4 w-4" />
                Destinasyonlar *
              </Label>
              <Input
                id="destinations"
                placeholder="Virgülle ayırarak yazın: Kapadokya, Göreme, Ürgüp"
                value={formData.destinations}
                onChange={(e) => setFormData({ ...formData, destinations: e.target.value })}
                required
              />
              <p className="text-xs text-muted-foreground">
                Hizmet verdiğiniz destinasyonları virgülle ayırarak yazın
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="activityCategories" className="flex items-center gap-2">
                <Tag className="h-4 w-4" />
                Aktivite Kategorileri *
              </Label>
              <Input
                id="activityCategories"
                placeholder="Örn: Balon Turu, ATV Turu, Rehberli Tur, Otel"
                value={formData.activityCategories}
                onChange={(e) => setFormData({ ...formData, activityCategories: e.target.value })}
                required
              />
              <p className="text-xs text-muted-foreground">
                Sunduğunuz hizmetleri virgülle ayırarak yazın
              </p>
            </div>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose} disabled={loading}>
              İptal
            </Button>
            <Button type="submit" disabled={loading}>
              {loading ? 'Kaydediliyor...' : 'Kayıt Ol'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
