import { ArrowLeft, Plus, Save, X } from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import { Textarea } from '@/components/ui/textarea';
import { providerServicesApi } from '@/db/api';
import { supabase } from '@/db/supabase';
import { useToast } from '@/hooks/use-toast';

const AVAILABLE_DESTINATIONS = [
  'Cappadocia',
  'Istanbul',
  'Antalya',
  'Pamukkale',
  'Ephesus',
  'Bodrum',
  'Fethiye',
  'Kas',
  'Marmaris',
  'Izmir',
];

const AVAILABLE_ACTIVITIES = [
  'hot-air-balloon',
  'atv',
  'horse-riding',
  'tour',
  'guide',
  'hiking',
  'diving',
  'paragliding',
  'boat-tour',
  'cultural-tour',
];

const DAILY_TOUR_TYPES = [
  { slug: 'red_tour', title: 'Kapadokya Red Tour', description: 'Göreme ve çevresindeki tarihi vadiler ve müzeler' },
  { slug: 'green_tour', title: 'Kapadokya Green Tour', description: 'Doğa, vadiler ve yeraltı şehirleri' },
  { slug: 'blue_tour', title: 'Kapadokya Blue Tour', description: 'Az bilinen vadiler ve manzara noktaları' },
  { slug: 'balloon_day', title: 'Balon + Hafif Günlük Tur', description: 'Sabah balon uçuşu sonrası hafif günlük gezi' },
  { slug: 'private_guide', title: 'Özel Rehber', description: 'Tamamen size özel planlanmış tur' },
];

const VEHICLE_TYPES = [
  'Minivan (6-8 kişi)',
  'Minibüs (9-15 kişi)',
  'Otobüs (16+ kişi)',
  'Lüks Araç',
  'SUV',
  '4x4',
];

const LANGUAGES = [
  'Türkçe',
  'English',
  'Español',
  'Français',
  'Deutsch',
  'Italiano',
  'Русский',
  '中文',
  '日本語',
  '한국어',
];

import { useAuth } from '@/contexts/AuthContext';

const ProviderSettings = () => {
  const { toast } = useToast();
  const navigate = useNavigate();
  const { profile, loading: authLoading } = useAuth();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  
  // Form state
  const [businessName, setBusinessName] = useState('');
  const [businessDescription, setBusinessDescription] = useState('');
  const [selectedDestinations, setSelectedDestinations] = useState<string[]>([]);
  const [selectedActivities, setSelectedActivities] = useState<string[]>([]);
  const [selectedDailyTours, setSelectedDailyTours] = useState<string[]>([]);
  const [selectedVehicles, setSelectedVehicles] = useState<string[]>([]);
  const [selectedLanguages, setSelectedLanguages] = useState<string[]>([]);
  const [customDestination, setCustomDestination] = useState('');
  const [customActivity, setCustomActivity] = useState('');
  const [customVehicle, setCustomVehicle] = useState('');
  const [customLanguage, setCustomLanguage] = useState('');

  useEffect(() => {
    if (!authLoading) {
      loadProviderSettings();
    }
  }, [authLoading]);

  const loadProviderSettings = async () => {
    try {
      setLoading(true);
      
      if (!profile) {
        navigate('/');
        return;
      }

      const service = await providerServicesApi.get(profile.id);
      
      if (service) {
        setBusinessName(service.business_name || '');
        setBusinessDescription(service.business_description || '');
        setSelectedDestinations(service.destinations || []);
        setSelectedActivities(service.activity_categories || []);
        setSelectedDailyTours(service.daily_tour_services || []);
        setSelectedVehicles(service.vehicle_types || []);
        setSelectedLanguages(service.languages || []);
      }
    } catch (error) {
      console.error('Error loading settings:', error);
      toast({
        title: 'Hata',
        description: 'Ayarlar yüklenemedi.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    try {
      setSaving(true);
      
      if (!profile) {
        throw new Error('Not authenticated');
      }

      if (selectedDestinations.length === 0) {
        toast({
          title: 'Doğrulama Hatası',
          description: 'Lütfen en az bir destinasyon seçin.',
          variant: 'destructive',
        });
        return;
      }

      if (selectedActivities.length === 0) {
        toast({
          title: 'Doğrulama Hatası',
          description: 'Lütfen en az bir aktivite kategorisi seçin.',
          variant: 'destructive',
        });
        return;
      }

      await providerServicesApi.upsert({
        provider_id: profile.id,
        business_name: businessName,
        business_description: businessDescription,
        destinations: selectedDestinations,
        activity_categories: selectedActivities,
        daily_tour_services: selectedDailyTours,
        vehicle_types: selectedVehicles,
        languages: selectedLanguages,
      });

      toast({
        title: 'Ayarlar Kaydedildi',
        description: 'Sağlayıcı ayarlarınız güncellendi.',
      });

      navigate('/provider-dashboard');
    } catch (error: any) {
      console.error('Save error:', error);
      toast({
        title: 'Kaydetme Başarısız',
        description: error.message || 'Ayarlar kaydedilemedi.',
        variant: 'destructive',
      });
    } finally {
      setSaving(false);
    }
  };

  const toggleDestination = (destination: string) => {
    setSelectedDestinations(prev =>
      prev.includes(destination)
        ? prev.filter(d => d !== destination)
        : [...prev, destination]
    );
  };

  const toggleActivity = (activity: string) => {
    setSelectedActivities(prev =>
      prev.includes(activity)
        ? prev.filter(a => a !== activity)
        : [...prev, activity]
    );
  };

  const addCustomDestination = () => {
    if (customDestination.trim() && !selectedDestinations.includes(customDestination.trim())) {
      setSelectedDestinations([...selectedDestinations, customDestination.trim()]);
      setCustomDestination('');
    }
  };

  const addCustomActivity = () => {
    if (customActivity.trim() && !selectedActivities.includes(customActivity.trim())) {
      setSelectedActivities([...selectedActivities, customActivity.trim()]);
      setCustomActivity('');
    }
  };

  const removeDestination = (destination: string) => {
    setSelectedDestinations(prev => prev.filter(d => d !== destination));
  };

  const removeActivity = (activity: string) => {
    setSelectedActivities(prev => prev.filter(a => a !== activity));
  };

  const toggleDailyTour = (tourSlug: string) => {
    setSelectedDailyTours(prev =>
      prev.includes(tourSlug)
        ? prev.filter(t => t !== tourSlug)
        : [...prev, tourSlug]
    );
  };

  const toggleVehicle = (vehicle: string) => {
    setSelectedVehicles(prev =>
      prev.includes(vehicle)
        ? prev.filter(v => v !== vehicle)
        : [...prev, vehicle]
    );
  };

  const toggleLanguage = (language: string) => {
    setSelectedLanguages(prev =>
      prev.includes(language)
        ? prev.filter(l => l !== language)
        : [...prev, language]
    );
  };

  const addCustomVehicle = () => {
    if (customVehicle.trim() && !selectedVehicles.includes(customVehicle.trim())) {
      setSelectedVehicles([...selectedVehicles, customVehicle.trim()]);
      setCustomVehicle('');
    }
  };

  const addCustomLanguage = () => {
    if (customLanguage.trim() && !selectedLanguages.includes(customLanguage.trim())) {
      setSelectedLanguages([...selectedLanguages, customLanguage.trim()]);
      setCustomLanguage('');
    }
  };

  const removeVehicle = (vehicle: string) => {
    setSelectedVehicles(prev => prev.filter(v => v !== vehicle));
  };

  const removeLanguage = (language: string) => {
    setSelectedLanguages(prev => prev.filter(l => l !== language));
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-background p-6">
        <div className="max-w-4xl mx-auto space-y-6">
          <Skeleton className="h-12 w-64" />
          <Skeleton className="h-96 w-full" />
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <div className="max-w-4xl mx-auto p-6 space-y-6">
        {/* Header */}
        <div className="flex items-center gap-4">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => navigate('/provider-dashboard')}
          >
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold">Sağlayıcı Ayarları</h1>
            <p className="text-muted-foreground">Hizmet alanlarınızı, tur tiplerini ve diğer detayları yapılandırın</p>
          </div>
        </div>

        {/* Business Info */}
        <Card>
          <CardHeader>
            <CardTitle>İşletme Bilgileri</CardTitle>
            <CardDescription>Gezginlere işletmeniz hakkında bilgi verin</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <label className="text-sm font-medium mb-2 block">İşletme Adı</label>
              <Input
                placeholder="örn: Kapadokya Macera Turları"
                value={businessName}
                onChange={(e) => setBusinessName(e.target.value)}
              />
            </div>
            <div>
              <label className="text-sm font-medium mb-2 block">Açıklama</label>
              <Textarea
                placeholder="Hizmetlerinizi ve sizi özel kılan özellikleri açıklayın..."
                rows={4}
                value={businessDescription}
                onChange={(e) => setBusinessDescription(e.target.value)}
              />
            </div>
          </CardContent>
        </Card>

        {/* Service Areas */}
        <Card>
          <CardHeader>
            <CardTitle>Hizmet Alanları (Destinasyonlar)</CardTitle>
            <CardDescription>
              Hizmet verdiğiniz destinasyonları seçin. Sadece bu lokasyonlar için talepler göreceksiniz.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* Selected Destinations */}
            {selectedDestinations.length > 0 && (
              <div>
                <p className="text-sm font-medium mb-2">Seçili Destinasyonlar:</p>
                <div className="flex flex-wrap gap-2">
                  {selectedDestinations.map(dest => (
                    <Badge key={dest} variant="secondary" className="gap-1">
                      {dest}
                      <button
                        onClick={() => removeDestination(dest)}
                        className="ml-1 hover:text-destructive"
                      >
                        <X className="h-3 w-3" />
                      </button>
                    </Badge>
                  ))}
                </div>
              </div>
            )}

            {/* Available Destinations */}
            <div>
              <p className="text-sm font-medium mb-2">Mevcut Destinasyonlar:</p>
              <div className="flex flex-wrap gap-2">
                {AVAILABLE_DESTINATIONS.filter(d => !selectedDestinations.includes(d)).map(dest => (
                  <Badge
                    key={dest}
                    variant="outline"
                    className="cursor-pointer hover:bg-primary hover:text-primary-foreground"
                    onClick={() => toggleDestination(dest)}
                  >
                    <Plus className="h-3 w-3 mr-1" />
                    {dest}
                  </Badge>
                ))}
              </div>
            </div>

            {/* Custom Destination */}
            <div>
              <p className="text-sm font-medium mb-2">Özel Destinasyon Ekle:</p>
              <div className="flex gap-2">
                <Input
                  placeholder="Destinasyon adı girin"
                  value={customDestination}
                  onChange={(e) => setCustomDestination(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && addCustomDestination()}
                />
                <Button onClick={addCustomDestination} size="icon">
                  <Plus className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Activity Categories */}
        <Card>
          <CardHeader>
            <CardTitle>Aktivite Kategorileri</CardTitle>
            <CardDescription>
              Sunduğunuz aktivite tiplerini seçin. Sadece bu aktiviteleri içeren talepler göreceksiniz.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* Selected Activities */}
            {selectedActivities.length > 0 && (
              <div>
                <p className="text-sm font-medium mb-2">Seçili Aktiviteler:</p>
                <div className="flex flex-wrap gap-2">
                  {selectedActivities.map(activity => (
                    <Badge key={activity} variant="secondary" className="gap-1">
                      {activity}
                      <button
                        onClick={() => removeActivity(activity)}
                        className="ml-1 hover:text-destructive"
                      >
                        <X className="h-3 w-3" />
                      </button>
                    </Badge>
                  ))}
                </div>
              </div>
            )}

            {/* Available Activities */}
            <div>
              <p className="text-sm font-medium mb-2">Mevcut Aktiviteler:</p>
              <div className="flex flex-wrap gap-2">
                {AVAILABLE_ACTIVITIES.filter(a => !selectedActivities.includes(a)).map(activity => (
                  <Badge
                    key={activity}
                    variant="outline"
                    className="cursor-pointer hover:bg-primary hover:text-primary-foreground"
                    onClick={() => toggleActivity(activity)}
                  >
                    <Plus className="h-3 w-3 mr-1" />
                    {activity}
                  </Badge>
                ))}
              </div>
            </div>

            {/* Custom Activity */}
            <div>
              <p className="text-sm font-medium mb-2">Özel Aktivite Ekle:</p>
              <div className="flex gap-2">
                <Input
                  placeholder="Aktivite tipi girin"
                  value={customActivity}
                  onChange={(e) => setCustomActivity(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && addCustomActivity()}
                />
                <Button onClick={addCustomActivity} size="icon">
                  <Plus className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Daily Tour Services */}
        <Card>
          <CardHeader>
            <CardTitle>Günlük Tur Servisleri</CardTitle>
            <CardDescription>
              Sunduğunuz günlük tur tiplerini seçin. AI önerileri bu turlara göre yapılacaktır.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* Selected Daily Tours */}
            {selectedDailyTours.length > 0 && (
              <div>
                <p className="text-sm font-medium mb-2">Seçili Turlar:</p>
                <div className="flex flex-wrap gap-2">
                  {selectedDailyTours.map(tourSlug => {
                    const tour = DAILY_TOUR_TYPES.find(t => t.slug === tourSlug);
                    return (
                      <Badge key={tourSlug} variant="secondary" className="gap-1">
                        {tour?.title || tourSlug}
                        <button
                          onClick={() => toggleDailyTour(tourSlug)}
                          className="ml-1 hover:text-destructive"
                        >
                          <X className="h-3 w-3" />
                        </button>
                      </Badge>
                    );
                  })}
                </div>
              </div>
            )}

            {/* Available Daily Tours */}
            <div>
              <p className="text-sm font-medium mb-2">Mevcut Turlar:</p>
              <div className="grid gap-3">
                {DAILY_TOUR_TYPES.filter(t => !selectedDailyTours.includes(t.slug)).map(tour => (
                  <div
                    key={tour.slug}
                    className="flex items-start gap-3 p-3 border rounded-lg cursor-pointer hover:bg-accent transition-colors"
                    onClick={() => toggleDailyTour(tour.slug)}
                  >
                    <div className="flex-shrink-0 mt-1">
                      <Plus className="h-4 w-4 text-primary" />
                    </div>
                    <div className="flex-1">
                      <p className="font-medium">{tour.title}</p>
                      <p className="text-sm text-muted-foreground">{tour.description}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Vehicle Types */}
        <Card>
          <CardHeader>
            <CardTitle>Araç Tipleri</CardTitle>
            <CardDescription>
              Sahip olduğunuz veya kullandığınız araç tiplerini belirtin.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* Selected Vehicles */}
            {selectedVehicles.length > 0 && (
              <div>
                <p className="text-sm font-medium mb-2">Seçili Araçlar:</p>
                <div className="flex flex-wrap gap-2">
                  {selectedVehicles.map(vehicle => (
                    <Badge key={vehicle} variant="secondary" className="gap-1">
                      {vehicle}
                      <button
                        onClick={() => removeVehicle(vehicle)}
                        className="ml-1 hover:text-destructive"
                      >
                        <X className="h-3 w-3" />
                      </button>
                    </Badge>
                  ))}
                </div>
              </div>
            )}

            {/* Available Vehicles */}
            <div>
              <p className="text-sm font-medium mb-2">Mevcut Araç Tipleri:</p>
              <div className="flex flex-wrap gap-2">
                {VEHICLE_TYPES.filter(v => !selectedVehicles.includes(v)).map(vehicle => (
                  <Badge
                    key={vehicle}
                    variant="outline"
                    className="cursor-pointer hover:bg-primary hover:text-primary-foreground"
                    onClick={() => toggleVehicle(vehicle)}
                  >
                    <Plus className="h-3 w-3 mr-1" />
                    {vehicle}
                  </Badge>
                ))}
              </div>
            </div>

            {/* Custom Vehicle */}
            <div>
              <p className="text-sm font-medium mb-2">Özel Araç Tipi Ekle:</p>
              <div className="flex gap-2">
                <Input
                  placeholder="Araç tipi girin"
                  value={customVehicle}
                  onChange={(e) => setCustomVehicle(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && addCustomVehicle()}
                />
                <Button onClick={addCustomVehicle} size="icon">
                  <Plus className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Languages */}
        <Card>
          <CardHeader>
            <CardTitle>Konuşulan Diller</CardTitle>
            <CardDescription>
              Rehberlik yapabileceğiniz dilleri seçin.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* Selected Languages */}
            {selectedLanguages.length > 0 && (
              <div>
                <p className="text-sm font-medium mb-2">Seçili Diller:</p>
                <div className="flex flex-wrap gap-2">
                  {selectedLanguages.map(language => (
                    <Badge key={language} variant="secondary" className="gap-1">
                      {language}
                      <button
                        onClick={() => removeLanguage(language)}
                        className="ml-1 hover:text-destructive"
                      >
                        <X className="h-3 w-3" />
                      </button>
                    </Badge>
                  ))}
                </div>
              </div>
            )}

            {/* Available Languages */}
            <div>
              <p className="text-sm font-medium mb-2">Mevcut Diller:</p>
              <div className="flex flex-wrap gap-2">
                {LANGUAGES.filter(l => !selectedLanguages.includes(l)).map(language => (
                  <Badge
                    key={language}
                    variant="outline"
                    className="cursor-pointer hover:bg-primary hover:text-primary-foreground"
                    onClick={() => toggleLanguage(language)}
                  >
                    <Plus className="h-3 w-3 mr-1" />
                    {language}
                  </Badge>
                ))}
              </div>
            </div>

            {/* Custom Language */}
            <div>
              <p className="text-sm font-medium mb-2">Özel Dil Ekle:</p>
              <div className="flex gap-2">
                <Input
                  placeholder="Dil adı girin"
                  value={customLanguage}
                  onChange={(e) => setCustomLanguage(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && addCustomLanguage()}
                />
                <Button onClick={addCustomLanguage} size="icon">
                  <Plus className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Save Button */}
        <div className="flex justify-end gap-4">
          <Button
            variant="outline"
            onClick={() => navigate('/provider-dashboard')}
            disabled={saving}
          >
            İptal
          </Button>
          <Button
            onClick={handleSave}
            disabled={saving || selectedDestinations.length === 0 || selectedActivities.length === 0}
          >
            <Save className="h-4 w-4 mr-2" />
            {saving ? 'Kaydediliyor...' : 'Ayarları Kaydet'}
          </Button>
        </div>
      </div>
    </div>
  );
};

export default ProviderSettings;
