import React, { useEffect, useState } from 'react';
import { FaStar } from 'react-icons/fa';
import woFeedbackWebFormService, { type WoFeedbackRecord } from '../services/woFeedbackWebFormService';

export interface WoFeedbackSummaryProps {
  workOrder: string;
}

const WoFeedbackSummary: React.FC<WoFeedbackSummaryProps> = ({ workOrder }) => {
  const [loading, setLoading] = useState(true);
  const [feedback, setFeedback] = useState<WoFeedbackRecord | null>(null);

  useEffect(() => {
    if (!workOrder) {
      setLoading(false);
      setFeedback(null);
      return;
    }

    let cancelled = false;

    (async () => {
      setLoading(true);
      try {
        const fb = await woFeedbackWebFormService.getFeedbackForWorkOrder(workOrder);
        if (!cancelled) setFeedback(fb);
      } catch {
        if (!cancelled) setFeedback(null);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();

    return () => { cancelled = true; };
  }, [workOrder]);

  if (loading || !feedback?.rating) return null;

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
      <h2 className="text-base font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
        WO Feedback
      </h2>
      <div className="flex items-start gap-3">
        <FaStar className="text-amber-500 mt-0.5 shrink-0" />
        <div>
          <p className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase mb-1">
            Rating
          </p>
          <p className="text-sm font-semibold text-gray-900 dark:text-white">
            {feedback.rating}
          </p>
          {feedback.requester_name && (
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
              <span className="font-medium">Requester:</span> {feedback.requester_name}
            </p>
          )}
          {feedback.comments && (
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
              <span className="font-medium">Comments:</span> {feedback.comments}
            </p>
          )}
        </div>
      </div>
    </div>
  );
};

export default WoFeedbackSummary;
