import { useState } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { toast } from '@/hooks/use-toast';
import { Star, X } from 'lucide-react';

interface ReviewModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  userId: string;
  productId?: string | null;
  orderId?: string | null;
  type: 'consulting' | 'bootcamp' | 'webinar' | 'general';
  contextLabel?: string;
  onSuccess?: () => void;
}

export function ReviewModal({
  open,
  onOpenChange,
  userId,
  productId,
  orderId,
  type,
  contextLabel,
  onSuccess,
}: ReviewModalProps) {
  const [rating, setRating] = useState(0);
  const [hoverRating, setHoverRating] = useState(0);
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async () => {
    if (rating === 0) {
      toast({ title: 'Error', description: 'Pilih rating terlebih dahulu', variant: 'destructive' });
      return;
    }
    if (!title.trim()) {
      toast({ title: 'Error', description: 'Judul tidak boleh kosong', variant: 'destructive' });
      return;
    }

    setSubmitting(true);
    const { error } = await supabase.from('reviews').insert({
      user_id: userId,
      product_id: productId || null,
      order_id: orderId || null,
      type,
      rating,
      title: title.trim(),
      body: body.trim() || null,
      is_approved: false,
    });

    if (error) {
      console.error('Review submit error:', error);
      toast({ title: 'Error', description: 'Gagal mengirim ulasan', variant: 'destructive' });
    } else {
      toast({ title: 'Berhasil', description: 'Terima kasih! Ulasan Anda akan ditinjau oleh admin.' });
      // Reset form
      setRating(0);
      setTitle('');
      setBody('');
      onOpenChange(false);
      onSuccess?.();
    }
    setSubmitting(false);
  };

  const handleClose = () => {
    if (!submitting) {
      onOpenChange(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Beri Ulasan</DialogTitle>
          {contextLabel && (
            <DialogDescription>{contextLabel}</DialogDescription>
          )}
        </DialogHeader>

        <div className="space-y-4 py-2">
          <div className="space-y-2">
            <label className="text-sm font-medium">Rating</label>
            <div className="flex gap-1">
              {[1, 2, 3, 4, 5].map((i) => (
                <button
                  key={i}
                  type="button"
                  onClick={() => setRating(i)}
                  onMouseEnter={() => setHoverRating(i)}
                  onMouseLeave={() => setHoverRating(0)}
                  className="p-1 transition-transform hover:scale-110"
                >
                  <Star
                    className={`w-8 h-8 ${
                      i <= (hoverRating || rating)
                        ? 'fill-primary text-primary'
                        : 'text-muted-foreground'
                    }`}
                  />
                </button>
              ))}
            </div>
          </div>

          <div className="space-y-2">
            <label className="text-sm font-medium">Judul</label>
            <Input
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="Ringkasan pengalaman Anda"
              className="border-2"
              maxLength={100}
            />
          </div>

          <div className="space-y-2">
            <label className="text-sm font-medium">Ulasan (Opsional)</label>
            <Textarea
              value={body}
              onChange={(e) => setBody(e.target.value)}
              placeholder="Ceritakan pengalaman Anda..."
              className="border-2 min-h-[100px]"
              maxLength={500}
            />
          </div>
        </div>

        <div className="flex gap-2 justify-end">
          <Button variant="outline" onClick={handleClose} disabled={submitting} className="border-2">
            Batal
          </Button>
          <Button onClick={handleSubmit} disabled={submitting}>
            {submitting ? 'Mengirim...' : 'Kirim Ulasan'}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
