import { ArrowLeft, Edit, Eye, EyeOff, Plus, Trash2 } from 'lucide-react';
import { 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 {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Skeleton } from '@/components/ui/skeleton';
import { Textarea } from '@/components/ui/textarea';
import { useAuth } from '@/contexts/AuthContext';
import { toursApi } from '@/db/api';
import { useToast } from '@/hooks/use-toast';
import type { Tour } from '@/types';
import { SERVICE_TYPE_METADATA, type ServiceTypeValue } from '@/types/service-types';

// Generate tour types from the shared enum
const TOUR_TYPES = Object.values(SERVICE_TYPE_METADATA).map(meta => ({
  value: meta.value,
  label: meta.label,
}));

const CURRENCIES = ['TRY', 'USD', 'EUR', 'GBP'];

const DESTINATIONS = [
  'Kapadokya',
  'İstanbul',
  'Antalya',
  'Bodrum',
  'Fethiye',
  'Pamukkale',
  'Efes',
  'Trabzon',
];

export default function AdminTours() {
  const navigate = useNavigate();
  const { user } = useAuth();
  const { toast } = useToast();

  const [tours, setTours] = useState<Tour[]>([]);
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingTour, setEditingTour] = useState<Tour | null>(null);
  const [saving, setSaving] = useState(false);

  // Form state
  const [formData, setFormData] = useState<{
    destination: string;
    name: string;
    type: ServiceTypeValue;
    covers: string;
    description: string;
    duration_hours: number;
    price_from: number;
    price_currency: string;
    commission_rate: number;
    image_url: string;
    includes: string;
    excludes: string;
    meeting_point: string;
    max_participants: number;
    min_participants: number;
    is_active: boolean;
  }>({
    destination: '',
    name: '',
    type: 'guided_tour',
    covers: '',
    description: '',
    duration_hours: 6,
    price_from: 0,
    price_currency: 'TRY',
    commission_rate: 0.15,
    image_url: '',
    includes: '',
    excludes: '',
    meeting_point: '',
    max_participants: 15,
    min_participants: 1,
    is_active: true,
  });

  // Check if user is admin
  useEffect(() => {
    if (user && user.role !== 'admin') {
      toast({
        title: 'Yetkisiz Erişim',
        description: 'Bu sayfaya erişim yetkiniz yok.',
        variant: 'destructive',
      });
      navigate('/');
    }
  }, [user, navigate, toast]);

  // Load tours
  useEffect(() => {
    loadTours();
  }, []);

  const loadTours = async () => {
    try {
      setLoading(true);
      const data = await toursApi.getAllTours();
      setTours(data);
    } catch (error: any) {
      console.error('Error loading tours:', error);
      toast({
        title: 'Hata',
        description: 'Turlar yüklenemedi.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleOpenDialog = (tour?: Tour) => {
    if (tour) {
      setEditingTour(tour);
      setFormData({
        destination: tour.destination,
        name: tour.name,
        type: tour.type,
        covers: tour.covers.join(', '),
        description: tour.description || '',
        duration_hours: Number(tour.duration_hours),
        price_from: Number(tour.price_from),
        price_currency: tour.price_currency,
        commission_rate: Number(tour.commission_rate),
        image_url: tour.image_url || '',
        includes: tour.includes?.join('\n') || '',
        excludes: tour.excludes?.join('\n') || '',
        meeting_point: tour.meeting_point || '',
        max_participants: tour.max_participants || 15,
        min_participants: tour.min_participants || 1,
        is_active: tour.is_active,
      });
    } else {
      setEditingTour(null);
      setFormData({
        destination: '',
        name: '',
        type: 'guided_tour',
        covers: '',
        description: '',
        duration_hours: 6,
        price_from: 0,
        price_currency: 'TRY',
        commission_rate: 0.15,
        image_url: '',
        includes: '',
        excludes: '',
        meeting_point: '',
        max_participants: 15,
        min_participants: 1,
        is_active: true,
      });
    }
    setDialogOpen(true);
  };

  const handleSave = async () => {
    try {
      setSaving(true);

      const tourData = {
        destination: formData.destination,
        name: formData.name,
        type: formData.type,
        covers: formData.covers.split(',').map(c => c.trim()).filter(Boolean),
        description: formData.description || undefined,
        duration_hours: formData.duration_hours,
        price_from: formData.price_from,
        price_currency: formData.price_currency,
        commission_rate: formData.commission_rate,
        image_url: formData.image_url || undefined,
        includes: formData.includes.split('\n').map(i => i.trim()).filter(Boolean),
        excludes: formData.excludes.split('\n').map(e => e.trim()).filter(Boolean),
        meeting_point: formData.meeting_point || undefined,
        max_participants: formData.max_participants,
        min_participants: formData.min_participants,
        is_active: formData.is_active,
      };

      if (editingTour) {
        await toursApi.updateTour(editingTour.id, tourData);
        toast({
          title: 'Başarılı',
          description: 'Tur güncellendi.',
        });
      } else {
        await toursApi.createTour(tourData);
        toast({
          title: 'Başarılı',
          description: 'Yeni tur oluşturuldu.',
        });
      }

      setDialogOpen(false);
      loadTours();
    } catch (error: any) {
      console.error('Save error:', error);
      toast({
        title: 'Hata',
        description: error.message || 'Tur kaydedilemedi.',
        variant: 'destructive',
      });
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (tourId: string) => {
    if (!confirm('Bu turu silmek istediğinizden emin misiniz?')) {
      return;
    }

    try {
      await toursApi.deleteTour(tourId);
      toast({
        title: 'Başarılı',
        description: 'Tur silindi.',
      });
      loadTours();
    } catch (error: any) {
      console.error('Delete error:', error);
      toast({
        title: 'Hata',
        description: error.message || 'Tur silinemedi.',
        variant: 'destructive',
      });
    }
  };

  const toggleActive = async (tour: Tour) => {
    try {
      await toursApi.updateTour(tour.id, { is_active: !tour.is_active });
      toast({
        title: 'Başarılı',
        description: `Tur ${!tour.is_active ? 'aktif' : 'pasif'} edildi.`,
      });
      loadTours();
    } catch (error: any) {
      console.error('Toggle error:', error);
      toast({
        title: 'Hata',
        description: 'Durum değiştirilemedi.',
        variant: 'destructive',
      });
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-background p-6">
        <div className="max-w-7xl mx-auto space-y-6">
          <Skeleton className="h-12 w-64" />
          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
            {[1, 2, 3, 4, 5, 6].map(i => (
              <Skeleton key={i} className="h-96" />
            ))}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <div className="max-w-7xl mx-auto p-6 space-y-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Button
              variant="ghost"
              size="icon"
              onClick={() => navigate('/')}
            >
              <ArrowLeft className="h-5 w-5" />
            </Button>
            <div>
              <h1 className="text-3xl font-bold">Tur Yönetimi</h1>
              <p className="text-muted-foreground">Turları oluştur, düzenle ve yönet</p>
            </div>
          </div>
          <Button onClick={() => handleOpenDialog()}>
            <Plus className="h-4 w-4 mr-2" />
            Yeni Tur Ekle
          </Button>
        </div>

        {/* Tours Grid */}
        {tours.length === 0 ? (
          <Card>
            <CardContent className="flex flex-col items-center justify-center py-12">
              <p className="text-muted-foreground mb-4">Henüz tur eklenmemiş</p>
              <Button onClick={() => handleOpenDialog()}>
                <Plus className="h-4 w-4 mr-2" />
                İlk Turu Ekle
              </Button>
            </CardContent>
          </Card>
        ) : (
          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
            {tours.map(tour => (
              <Card key={tour.id} className={!tour.is_active ? 'opacity-60' : ''}>
                {tour.image_url && (
                  <div className="relative h-48 overflow-hidden">
                    <img
                      src={tour.image_url}
                      alt={tour.name}
                      className="w-full h-full object-cover"
                    />
                    <Badge
                      className="absolute top-2 right-2"
                      variant={tour.is_active ? 'default' : 'secondary'}
                    >
                      {tour.is_active ? 'Aktif' : 'Pasif'}
                    </Badge>
                  </div>
                )}
                <CardHeader>
                  <CardTitle className="text-lg line-clamp-2">{tour.name}</CardTitle>
                  <CardDescription>
                    <Badge variant="outline" className="text-xs">
                      {TOUR_TYPES.find(t => t.value === tour.type)?.label || tour.type}
                    </Badge>
                    <span className="mx-2">•</span>
                    <span>{tour.destination}</span>
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-muted-foreground">Süre:</span>
                    <span className="font-medium">{tour.duration_hours} saat</span>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-muted-foreground">Fiyat:</span>
                    <span className="font-medium">
                      {Number(tour.price_from).toLocaleString('tr-TR')} {tour.price_currency}
                    </span>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-muted-foreground">Komisyon:</span>
                    <span className="font-medium">%{Math.round(Number(tour.commission_rate) * 100)}</span>
                  </div>
                  <div className="flex gap-2 pt-2">
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex-1"
                      onClick={() => toggleActive(tour)}
                    >
                      {tour.is_active ? (
                        <>
                          <EyeOff className="h-4 w-4 mr-1" />
                          Pasif Yap
                        </>
                      ) : (
                        <>
                          <Eye className="h-4 w-4 mr-1" />
                          Aktif Yap
                        </>
                      )}
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleOpenDialog(tour)}
                    >
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleDelete(tour.id)}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}

        {/* Create/Edit Dialog */}
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>{editingTour ? 'Turu Düzenle' : 'Yeni Tur Ekle'}</DialogTitle>
              <DialogDescription>
                Tur bilgilerini girin. Tüm alanlar zorunludur.
              </DialogDescription>
            </DialogHeader>

            <div className="space-y-4">
              {/* Destination */}
              <div>
                <Label htmlFor="destination">Destinasyon</Label>
                <Select
                  value={formData.destination}
                  onValueChange={(value) => setFormData({ ...formData, destination: value })}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Destinasyon seçin" />
                  </SelectTrigger>
                  <SelectContent>
                    {DESTINATIONS.map(dest => (
                      <SelectItem key={dest} value={dest}>{dest}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* Name */}
              <div>
                <Label htmlFor="name">Tur Adı</Label>
                <Input
                  id="name"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="örn: Kapadokya Red Tour"
                />
              </div>

              {/* Type */}
              <div>
                <Label htmlFor="type">Tur Tipi</Label>
                <Select
                  value={formData.type}
                  onValueChange={(value) => setFormData({ ...formData, type: value as ServiceTypeValue })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {TOUR_TYPES.map(type => (
                      <SelectItem key={type.value} value={type.value}>
                        {type.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* Covers */}
              <div>
                <Label htmlFor="covers">Kapsadığı Yerler (virgülle ayırın)</Label>
                <Input
                  id="covers"
                  value={formData.covers}
                  onChange={(e) => setFormData({ ...formData, covers: e.target.value })}
                  placeholder="örn: Göreme, Uçhisar, Paşabağ"
                />
              </div>

              {/* Description */}
              <div>
                <Label htmlFor="description">Açıklama</Label>
                <Textarea
                  id="description"
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  placeholder="Tur hakkında detaylı açıklama..."
                  rows={3}
                />
              </div>

              {/* Duration & Price */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="duration_hours">Süre (saat)</Label>
                  <Input
                    id="duration_hours"
                    type="number"
                    value={formData.duration_hours}
                    onChange={(e) => setFormData({ ...formData, duration_hours: Number(e.target.value) })}
                  />
                </div>
                <div>
                  <Label htmlFor="price_from">Başlangıç Fiyatı</Label>
                  <Input
                    id="price_from"
                    type="number"
                    value={formData.price_from}
                    onChange={(e) => setFormData({ ...formData, price_from: Number(e.target.value) })}
                  />
                </div>
              </div>

              {/* Currency & Commission */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="price_currency">Para Birimi</Label>
                  <Select
                    value={formData.price_currency}
                    onValueChange={(value) => setFormData({ ...formData, price_currency: value })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {CURRENCIES.map(curr => (
                        <SelectItem key={curr} value={curr}>{curr}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label htmlFor="commission_rate">Komisyon Oranı (0-1)</Label>
                  <Input
                    id="commission_rate"
                    type="number"
                    step="0.01"
                    value={formData.commission_rate}
                    onChange={(e) => setFormData({ ...formData, commission_rate: Number(e.target.value) })}
                  />
                </div>
              </div>

              {/* Participants */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="min_participants">Min Katılımcı</Label>
                  <Input
                    id="min_participants"
                    type="number"
                    value={formData.min_participants}
                    onChange={(e) => setFormData({ ...formData, min_participants: Number(e.target.value) })}
                  />
                </div>
                <div>
                  <Label htmlFor="max_participants">Max Katılımcı</Label>
                  <Input
                    id="max_participants"
                    type="number"
                    value={formData.max_participants}
                    onChange={(e) => setFormData({ ...formData, max_participants: Number(e.target.value) })}
                  />
                </div>
              </div>

              {/* Image URL */}
              <div>
                <Label htmlFor="image_url">Görsel URL</Label>
                <Input
                  id="image_url"
                  value={formData.image_url}
                  onChange={(e) => setFormData({ ...formData, image_url: e.target.value })}
                  placeholder="https://..."
                />
              </div>

              {/* Meeting Point */}
              <div>
                <Label htmlFor="meeting_point">Buluşma Noktası</Label>
                <Input
                  id="meeting_point"
                  value={formData.meeting_point}
                  onChange={(e) => setFormData({ ...formData, meeting_point: e.target.value })}
                  placeholder="örn: Göreme Meydanı"
                />
              </div>

              {/* Includes */}
              <div>
                <Label htmlFor="includes">Dahil Olanlar (her satıra bir tane)</Label>
                <Textarea
                  id="includes"
                  value={formData.includes}
                  onChange={(e) => setFormData({ ...formData, includes: e.target.value })}
                  placeholder="Rehber&#10;Öğle yemeği&#10;Müze girişleri"
                  rows={3}
                />
              </div>

              {/* Excludes */}
              <div>
                <Label htmlFor="excludes">Dahil Olmayanlar (her satıra bir tane)</Label>
                <Textarea
                  id="excludes"
                  value={formData.excludes}
                  onChange={(e) => setFormData({ ...formData, excludes: e.target.value })}
                  placeholder="İçecekler&#10;Kişisel harcamalar"
                  rows={2}
                />
              </div>

              {/* Active Status */}
              <div className="flex items-center gap-2">
                <input
                  type="checkbox"
                  id="is_active"
                  checked={formData.is_active}
                  onChange={(e) => setFormData({ ...formData, is_active: e.target.checked })}
                  className="h-4 w-4"
                />
                <Label htmlFor="is_active">Aktif</Label>
              </div>
            </div>

            <DialogFooter>
              <Button variant="outline" onClick={() => setDialogOpen(false)} disabled={saving}>
                İptal
              </Button>
              <Button onClick={handleSave} disabled={saving}>
                {saving ? 'Kaydediliyor...' : 'Kaydet'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>
    </div>
  );
}
