'use client';

import { useState } from 'react';
import { Star } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { api } from '@/lib/api';

function StarPicker({
  label,
  value,
  onChange,
}: {
  label: string;
  value: number;
  onChange: (value: number) => void;
}) {
  const [hover, setHover] = useState(0);

  return (
    <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
      <span className="text-sm font-medium text-slate-700">{label}</span>
      <div className="flex items-center gap-0.5">
        {[1, 2, 3, 4, 5].map((star) => (
          <button
            key={star}
            type="button"
            className="p-0.5 rounded hover:scale-110 transition-transform"
            onMouseEnter={() => setHover(star)}
            onMouseLeave={() => setHover(0)}
            onClick={() => onChange(star)}
            aria-label={`${star} star${star > 1 ? 's' : ''}`}
          >
            <Star
              className={cn(
                'h-6 w-6',
                (hover || value) >= star
                  ? 'fill-yellow-400 text-yellow-400'
                  : 'fill-slate-200 text-slate-200'
              )}
            />
          </button>
        ))}
      </div>
    </div>
  );
}

interface ReviewFormProps {
  jobId?: string;
  hireInvitationId?: string;
  workerName: string;
  onSubmitted?: () => void;
}

export function ReviewForm({
  jobId,
  hireInvitationId,
  workerName,
  onSubmitted,
}: ReviewFormProps) {
  const [qualityRating, setQualityRating] = useState(0);
  const [communicationRating, setCommunicationRating] = useState(0);
  const [punctualityRating, setPunctualityRating] = useState(0);
  const [comment, setComment] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');

  const canSubmit =
    qualityRating > 0 &&
    communicationRating > 0 &&
    punctualityRating > 0 &&
    !submitting &&
    Boolean(jobId || hireInvitationId);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!canSubmit) return;

    setSubmitting(true);
    setError('');
    try {
      await api('/reviews', {
        method: 'POST',
        body: JSON.stringify({
          ...(jobId ? { jobId } : {}),
          ...(hireInvitationId ? { hireInvitationId } : {}),
          qualityRating,
          communicationRating,
          punctualityRating,
          comment: comment.trim() || undefined,
        }),
      });
      onSubmitted?.();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to submit review');
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <Card>
      <CardContent className="p-5">
        <h3 className="font-bold text-slate-900 mb-1">Rate {workerName}</h3>
        <p className="text-sm text-muted mb-4">
          Only customers who hired this worker can leave a review.
        </p>
        <form onSubmit={handleSubmit} className="space-y-4">
          <StarPicker label="Quality of work" value={qualityRating} onChange={setQualityRating} />
          <StarPicker
            label="Communication"
            value={communicationRating}
            onChange={setCommunicationRating}
          />
          <StarPicker label="Punctuality" value={punctualityRating} onChange={setPunctualityRating} />
          <div>
            <label htmlFor="review-comment" className="text-sm font-medium text-slate-700">
              Comment (optional)
            </label>
            <textarea
              id="review-comment"
              value={comment}
              onChange={(e) => setComment(e.target.value)}
              maxLength={2000}
              rows={3}
              placeholder="Share your experience working with this worker…"
              className="search-input mt-1.5 w-full min-h-[88px] py-2 resize-y"
            />
          </div>
          {error && <p className="text-sm text-red-600">{error}</p>}
          <Button type="submit" disabled={!canSubmit} className="w-full sm:w-auto">
            {submitting ? 'Submitting…' : 'Submit review'}
          </Button>
        </form>
      </CardContent>
    </Card>
  );
}
