'use client';
import { useState } from 'react';
import { TrainingProgram } from '../../hr/training/trainingData';

interface ObjectiveRating {
  objective: string;
  rating: number;
  comment: string;
}

interface Props {
  program: TrainingProgram;
  employeeName: string;
  onClose: () => void;
  onSubmit: (data: {
    programId: string;
    programTitle: string;
    overallRating: number;
    overallComment: string;
    objectiveRatings: ObjectiveRating[];
    date: string;
  }) => void;
}

function StarPicker({ value, onChange }: { value: number; onChange: (v: number) => void }) {
  const [hover, setHover] = useState(0);
  return (
    <div className="flex items-center gap-1">
      {[1, 2, 3, 4, 5].map(i => (
        <button key={i} type="button"
          onMouseEnter={() => setHover(i)}
          onMouseLeave={() => setHover(0)}
          onClick={() => onChange(i)}
          className="w-7 h-7 flex items-center justify-center cursor-pointer">
          <i className={`${(hover || value) >= i ? 'ri-star-fill' : 'ri-star-line'} text-yellow-400 text-xl`}></i>
        </button>
      ))}
      {value > 0 && (
        <span className="text-xs text-gray-500 ml-1">{value}/5</span>
      )}
    </div>
  );
}

const RATING_LABELS = ['', 'Poor', 'Fair', 'Good', 'Very Good', 'Excellent'];

export default function ReactionSurveyModal({ program, employeeName, onClose, onSubmit }: Props) {
  const [overallRating, setOverallRating] = useState(0);
  const [overallComment, setOverallComment] = useState('');
  const [objectiveRatings, setObjectiveRatings] = useState<ObjectiveRating[]>(
    (program.objectives || []).map(obj => ({ objective: obj, rating: 0, comment: '' }))
  );
  const [submitted, setSubmitted] = useState(false);

  const updateObjective = (index: number, field: 'rating' | 'comment', value: string | number) => {
    setObjectiveRatings(prev => prev.map((r, i) => i === index ? { ...r, [field]: value } : r));
  };

  const allRated = overallRating > 0 && objectiveRatings.every(r => r.rating > 0);

  const handleSubmit = () => {
    if (!allRated) return;
    const today = new Date().toISOString().split('T')[0];
    onSubmit({
      programId: program.id,
      programTitle: program.title,
      overallRating,
      overallComment,
      objectiveRatings,
      date: today,
    });
    setSubmitted(true);
  };

  if (submitted) {
    return (
      <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
        <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-8 text-center">
          <div className="w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto mb-4">
            <i className="ri-emotion-happy-line text-green-600 text-3xl"></i>
          </div>
          <h3 className="font-bold text-gray-800 text-xl mb-2">Feedback Submitted!</h3>
          <p className="text-sm text-gray-500 mb-2">Thank you, {employeeName.split(' ')[0]}! Your reaction has been recorded.</p>
          <p className="text-xs text-gray-400 mb-6">Your feedback is now visible in your My Reaction tab and has been shared with HR.</p>
          <button onClick={onClose}
            className="w-full py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap"
            style={{ background: '#b22698' }}>
            Done
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div className="px-6 py-4 border-b border-gray-100" style={{ background: '#b22698' }}>
          <div className="flex items-start justify-between">
            <div>
              <h2 className="text-white font-bold text-lg">Reaction Survey</h2>
              <p className="text-pink-200 text-sm mt-0.5">{program.title}</p>
            </div>
            <button onClick={onClose} className="w-8 h-8 flex items-center justify-center rounded-lg bg-white/20 cursor-pointer">
              <i className="ri-close-line text-white"></i>
            </button>
          </div>
        </div>

        <div className="p-6 space-y-6">
          <div className="bg-blue-50 border border-blue-200 rounded-xl px-4 py-3 text-xs text-blue-800">
            <strong>Instructions:</strong> Please rate how each course objective/topic was delivered to you. Your honest feedback helps improve future training programs.
          </div>

          <div className="bg-white border border-gray-200 rounded-xl p-4">
            <h3 className="font-semibold text-gray-800 mb-3">Overall Course Rating *</h3>
            <StarPicker value={overallRating} onChange={setOverallRating} />
            {overallRating > 0 && (
              <p className="text-xs text-amber-600 mt-1 font-medium">{RATING_LABELS[overallRating]}</p>
            )}
            <div className="mt-3">
              <label className="block text-xs font-medium text-gray-600 mb-1">Overall Comments</label>
              <textarea value={overallComment} onChange={e => setOverallComment(e.target.value)}
                rows={2} maxLength={500} placeholder="Share your overall experience with this training..."
                className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none resize-none" />
            </div>
          </div>

          <div>
            <h3 className="font-semibold text-gray-800 mb-3">Rate Each Objective/Topic *</h3>
            <div className="space-y-3">
              {(objectiveRatings || []).map((obj, i) => (
                <div key={i} className="border border-gray-200 rounded-xl p-4">
                  <div className="flex items-start gap-3 mb-3">
                    <div className="w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0" style={{ background: '#b22698' }}>
                      {i + 1}
                    </div>
                    <p className="text-sm font-medium text-gray-800">{obj.objective}</p>
                  </div>
                  <div className="ml-9">
                    <label className="block text-xs text-gray-500 mb-1">How well was this topic delivered?</label>
                    <StarPicker value={obj.rating} onChange={v => updateObjective(i, 'rating', v)} />
                    {obj.rating > 0 && (
                      <p className="text-xs text-amber-600 mt-1 font-medium">{RATING_LABELS[obj.rating]}</p>
                    )}
                    <div className="mt-2">
                      <label className="block text-xs text-gray-500 mb-1">Comments (optional)</label>
                      <input value={obj.comment} onChange={e => updateObjective(i, 'comment', e.target.value)}
                        placeholder="Any specific feedback on this topic..."
                        className="w-full border border-gray-200 rounded-lg px-3 py-2 text-xs outline-none" />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {!allRated && (
            <p className="text-xs text-amber-600 text-center">Please rate all objectives and the overall course before submitting.</p>
          )}
        </div>

        <div className="px-6 py-4 border-t border-gray-100 flex gap-3 justify-end">
          <button onClick={onClose}
            className="px-4 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">
            Cancel
          </button>
          <button onClick={handleSubmit} disabled={!allRated}
            className="px-6 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap"
            style={{ background: '#b22698' }}>
            Submit Feedback
          </button>
        </div>
      </div>
    </div>
  );
}
