import { useState } from 'react';
import { createShare, TrackShare, TrackShareError } from '../services/trackShareService';
import { ShareLinkDisplay } from './ShareLinkDisplay';
import { Dialog, DialogHeader, DialogBody, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { useToast } from '@/hooks/useToast';
import { Share2 } from 'lucide-react';

/**
 * TrackShareDialog Component
 * T0310: Composant dialog pour créer et gérer les liens de partage de tracks
 */

interface TrackShareDialogProps {
  open: boolean;
  onClose: () => void;
  trackId: number;
}

export function TrackShareDialog({ open, onClose, trackId }: TrackShareDialogProps) {
  const [readPermission, setReadPermission] = useState(true);
  const [downloadPermission, setDownloadPermission] = useState(false);
  const [expiresAt, setExpiresAt] = useState<string>('');
  const [share, setShare] = useState<TrackShare | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const { toast } = useToast();

  const handleCreateShare = async () => {
    setLoading(true);
    setError(null);

    try {
      const permissions = [];
      if (readPermission) permissions.push('read');
      if (downloadPermission) permissions.push('download');

      if (permissions.length === 0) {
        setError('Veuillez sélectionner au moins une permission');
        setLoading(false);
        return;
      }

      const data = {
        permissions: permissions.join(','),
        expires_at: expiresAt ? new Date(expiresAt).toISOString() : undefined,
      };

      const newShare = await createShare(trackId, data);
      setShare(newShare);
      toast.success('Lien de partage créé avec succès');
    } catch (err) {
      let errorMessage = 'Échec de la création du lien de partage';
      if (err instanceof TrackShareError) {
        errorMessage = err.message;
      } else if (err instanceof Error) {
        errorMessage = err.message;
      }
      setError(errorMessage);
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    // Reset state when closing
    setShare(null);
    setReadPermission(true);
    setDownloadPermission(false);
    setExpiresAt('');
    setError(null);
    onClose();
  };

  const handleCreateNew = () => {
    setShare(null);
    setReadPermission(true);
    setDownloadPermission(false);
    setExpiresAt('');
    setError(null);
  };

  // Get minimum date (today) for expiration date picker
  const getMinDate = () => {
    const now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
    return now.toISOString().slice(0, 16);
  };

  return (
    <Dialog open={open} onClose={handleClose} title="Partager le track" size="lg">
      <DialogBody>
        {!share ? (
          <div className="space-y-6">
            {/* Permissions Section */}
            <div className="space-y-3">
              <Label className="text-base font-semibold">Permissions</Label>
              <div className="space-y-3">
                <div className="flex items-center space-x-3">
                  <Checkbox
                    id="read"
                    checked={readPermission}
                    onCheckedChange={(checked) => setReadPermission(checked === true)}
                  />
                  <Label htmlFor="read" className="text-sm font-normal cursor-pointer">
                    Lecture - Permet de visualiser le track
                  </Label>
                </div>
                <div className="flex items-center space-x-3">
                  <Checkbox
                    id="download"
                    checked={downloadPermission}
                    onCheckedChange={(checked) => setDownloadPermission(checked === true)}
                  />
                  <Label htmlFor="download" className="text-sm font-normal cursor-pointer">
                    Téléchargement - Permet de télécharger le track
                  </Label>
                </div>
              </div>
            </div>

            {/* Expiration Section */}
            <div className="space-y-2">
              <Label htmlFor="expires_at" className="text-base font-semibold">
                Date d'expiration (optionnel)
              </Label>
              <Input
                id="expires_at"
                type="datetime-local"
                value={expiresAt}
                onChange={(e) => setExpiresAt(e.target.value)}
                min={getMinDate()}
                placeholder="Sélectionner une date d'expiration"
              />
              <p className="text-xs text-muted-foreground">
                Le lien de partage expirera automatiquement à cette date
              </p>
            </div>

            {/* Error Display */}
            {error && (
              <Alert variant="destructive">
                <AlertDescription>{error}</AlertDescription>
              </Alert>
            )}

            {/* Loading State */}
            {loading && (
              <div className="flex items-center justify-center py-4">
                <LoadingSpinner size="sm" />
                <span className="ml-2 text-sm text-muted-foreground">
                  Création du lien de partage...
                </span>
              </div>
            )}
          </div>
        ) : (
          <ShareLinkDisplay share={share} />
        )}
      </DialogBody>

      <DialogFooter>
        {!share ? (
          <>
            <Button variant="outline" onClick={handleClose} disabled={loading}>
              Annuler
            </Button>
            <Button
              onClick={handleCreateShare}
              disabled={loading || (!readPermission && !downloadPermission)}
            >
              {loading ? (
                <>
                  <LoadingSpinner size="sm" className="mr-2" />
                  Création...
                </>
              ) : (
                <>
                  <Share2 className="h-4 w-4 mr-2" />
                  Créer le lien de partage
                </>
              )}
            </Button>
          </>
        ) : (
          <>
            <Button variant="outline" onClick={handleCreateNew}>
              Créer un nouveau lien
            </Button>
            <Button onClick={handleClose}>Fermer</Button>
          </>
        )}
      </DialogFooter>
    </Dialog>
  );
}

