import { Check, Copy, Globe, Lock, Share2 } from 'lucide-react';
import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { tripsApi } from '@/db/api';
import { useToast } from '@/hooks/use-toast';
import { generateTripSlug } from '@/lib/slug';

interface ShareDialogProps {
  trip: any;
  onTripUpdate?: (updatedTrip: any) => void;
}

/**
 * ShareDialog - Seyahat paylaşım dialogu
 * Public link oluşturma ve kopyalama
 */
export function ShareDialog({ trip, onTripUpdate }: ShareDialogProps) {
  const { toast } = useToast();
  const [isPublic, setIsPublic] = useState(trip?.is_public || false);
  const [publicSlug, setPublicSlug] = useState(trip?.public_slug || '');
  const [isLoading, setIsLoading] = useState(false);
  const [isCopied, setIsCopied] = useState(false);
  const [isOpen, setIsOpen] = useState(false);

  // Public link URL'i
  const publicUrl = publicSlug 
    ? `${window.location.origin}/trip/${publicSlug}`
    : '';

  // Public durumunu değiştir
  const handleTogglePublic = async (checked: boolean) => {
    if (!trip?.id) return;

    try {
      setIsLoading(true);

      if (checked) {
        // Public yap - slug oluştur
        let slug = publicSlug;
        if (!slug) {
          slug = generateTripSlug(trip.title, trip.destination);
        }

        const updatedTrip = await tripsApi.makePublic(trip.id, slug);
        setIsPublic(true);
        setPublicSlug(slug);
        
        if (onTripUpdate) {
          onTripUpdate(updatedTrip);
        }

        toast({
          title: 'Seyahat paylaşıma açıldı',
          description: 'Artık linki paylaşabilirsiniz',
        });
      } else {
        // Private yap
        const updatedTrip = await tripsApi.makePrivate(trip.id);
        setIsPublic(false);
        
        if (onTripUpdate) {
          onTripUpdate(updatedTrip);
        }

        toast({
          title: 'Seyahat gizlendi',
          description: 'Link artık çalışmayacak',
        });
      }
    } catch (error: any) {
      console.error('Paylaşım durumu değiştirme hatası:', error);
      toast({
        title: 'Hata',
        description: 'Bir hata oluştu, lütfen tekrar deneyin',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

  // Linki kopyala
  const handleCopyLink = async () => {
    if (!publicUrl) return;

    try {
      await navigator.clipboard.writeText(publicUrl);
      setIsCopied(true);
      
      toast({
        title: 'Link kopyalandı',
        description: 'Paylaşım linki panoya kopyalandı',
      });

      setTimeout(() => setIsCopied(false), 2000);
    } catch (error) {
      console.error('Kopyalama hatası:', error);
      toast({
        title: 'Hata',
        description: 'Link kopyalanamadı',
        variant: 'destructive',
      });
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogTrigger asChild>
        <Button variant="ghost" size="icon" className="h-9 w-9 text-foreground">
          <Share2 className="h-4 w-4" />
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Seyahati Paylaş</DialogTitle>
          <DialogDescription>
            Seyahatinizi herkese açık bir link ile paylaşın
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          {/* Public/Private Toggle */}
          <div className="flex items-center justify-between space-x-2">
            <div className="flex items-center space-x-2">
              {isPublic ? (
                <Globe className="h-4 w-4 text-primary" />
              ) : (
                <Lock className="h-4 w-4 text-muted-foreground" />
              )}
              <Label htmlFor="public-toggle" className="cursor-pointer">
                {isPublic ? 'Herkese Açık' : 'Gizli'}
              </Label>
            </div>
            <Switch
              id="public-toggle"
              checked={isPublic}
              onCheckedChange={handleTogglePublic}
              disabled={isLoading}
            />
          </div>

          {/* Public Link */}
          {isPublic && publicUrl && (
            <div className="space-y-2">
              <Label htmlFor="public-link">Paylaşım Linki</Label>
              <div className="flex flex-col sm:flex-row gap-2">
                <Input
                  id="public-link"
                  value={publicUrl}
                  readOnly
                  className="flex-1 text-xs sm:text-sm"
                />
                <Button
                  type="button"
                  size="sm"
                  variant="outline"
                  onClick={handleCopyLink}
                  disabled={!publicUrl}
                  className="w-full sm:w-auto shrink-0 gap-2"
                >
                  {isCopied ? (
                    <>
                      <Check className="h-4 w-4 text-green-500" />
                      <span className="sm:hidden">Kopyalandı</span>
                    </>
                  ) : (
                    <>
                      <Copy className="h-4 w-4" />
                      <span className="sm:hidden">Kopyala</span>
                    </>
                  )}
                </Button>
              </div>
              <p className="text-xs text-muted-foreground italic">
                Bu linke sahip olan herkes seyahatinizi görüntüleyebilir (salt okunur)
              </p>
            </div>
          )}

          {/* Info */}
          {!isPublic && (
            <div className="rounded-lg bg-muted p-3">
              <p className="text-sm text-muted-foreground">
                Seyahatiniz şu anda gizli. Paylaşmak için yukarıdaki anahtarı açın.
              </p>
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}
