'use client';
import { useState } from 'react';
import { Appraisal, COMPANY_GOALS, DEPARTMENT_GOALS, RATING_LABELS, RATING_BG, getDeptGoals, GoalRating } from '../../hr/performance/performanceData';

interface Props {
  appraisal: Appraisal;
  onSave: (updated: Appraisal) => void;
  onClose: () => void;
}

export default function SelfAssessmentForm({ appraisal, onSave, onClose }: Props) {
  const deptGoals = getDeptGoals(appraisal.dept);
  const relevantCompanyGoals = COMPANY_GOALS;

  const [step, setStep] = useState<'company' | 'dept' | 'comments' | 'review'>('company');
  const [cgRatings, setCGRatings] = useState<Record<string, { rating: number; comment: string }>>(
    Object.fromEntries(appraisal.companyGoalRatings.map(r => [r.goalId, { rating: r.selfRating, comment: r.selfComment }]))
  );
  const [dgRatings, setDGRatings] = useState<Record<string, { rating: number; comment: string }>>(
    Object.fromEntries(appraisal.deptGoalRatings.map(r => [r.goalId, { rating: r.selfRating, comment: r.selfComment }]))
  );
  const [comments, setComments] = useState(appraisal.selfAssessmentComments || '');
  const [selectedCGIds, setSelectedCGIds] = useState<string[]>(
    appraisal.companyGoalRatings.length > 0
      ? appraisal.companyGoalRatings.map(r => r.goalId)
      : []
  );
  const [selectedDGIds, setSelectedDGIds] = useState<string[]>(
    appraisal.deptGoalRatings.length > 0
      ? appraisal.deptGoalRatings.map(r => r.goalId)
      : deptGoals.map(g => g.id)
  );

  const toggleCG = (id: string) => {
    setSelectedCGIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  };

  const toggleDG = (id: string) => {
    setSelectedDGIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  };

  const handleSubmit = () => {
    const companyGoalRatings: GoalRating[] = selectedCGIds.map(id => ({
      goalId: id,
      selfRating: cgRatings[id]?.rating || 3,
      selfComment: cgRatings[id]?.comment || '',
    }));
    const deptGoalRatings: GoalRating[] = selectedDGIds.map(id => ({
      goalId: id,
      selfRating: dgRatings[id]?.rating || 3,
      selfComment: dgRatings[id]?.comment || '',
    }));
    const updated: Appraisal = {
      ...appraisal,
      status: 'Submitted',
      companyGoalRatings,
      deptGoalRatings,
      selfAssessmentComments: comments,
      submittedDate: new Date().toISOString().split('T')[0],
    };
    onSave(updated);
  };

  const steps = [
    { id: 'company', label: 'Company Goals', icon: 'ri-building-line' },
    { id: 'dept', label: 'Dept Goals', icon: 'ri-flag-line' },
    { id: 'comments', label: 'Comments', icon: 'ri-chat-3-line' },
    { id: 'review', label: 'Review & Submit', icon: 'ri-checkbox-circle-line' },
  ];
  const stepIdx = steps.findIndex(s => s.id === step);

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl w-full max-w-3xl max-h-[92vh] flex flex-col shadow-2xl">
        <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: '#b828a0' }}>
          <div>
            <h2 className="text-white font-bold">Self-Assessment — {appraisal.period}</h2>
            <p className="text-pink-200 text-xs mt-0.5">Rate yourself on company and department goals (1–5 scale)</p>
          </div>
          <button onClick={onClose} className="w-8 h-8 flex items-center justify-center cursor-pointer">
            <i className="ri-close-line text-white text-xl"></i>
          </button>
        </div>

        <div className="px-6 py-3 border-b border-gray-100 bg-gray-50">
          <div className="flex items-center gap-2">
            {steps.map((s, i) => (
              <div key={s.id} className="flex items-center gap-2">
                <button
                  onClick={() => i <= stepIdx && setStep(s.id as any)}
                  className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium whitespace-nowrap transition-all ${i <= stepIdx ? 'cursor-pointer' : 'cursor-default'}`}
                  style={step === s.id ? { background: '#b828a0', color: 'white' } : i < stepIdx ? { background: '#dcfce7', color: '#15803d' } : { background: 'white', color: '#9ca3af', border: '1px solid #e5e7eb' }}
                >
                  <i className={`${i < stepIdx ? 'ri-checkbox-circle-fill' : s.icon} text-xs`}></i>
                  {s.label}
                </button>
                {i < steps.length - 1 && <i className="ri-arrow-right-s-line text-gray-300 text-sm"></i>}
              </div>
            ))}
          </div>
        </div>

        <div className="flex-1 overflow-y-auto px-6 py-5">
          <div className="bg-blue-50 border border-blue-100 rounded-xl p-3 mb-4 flex items-start gap-2">
            <div className="w-4 h-4 flex items-center justify-center mt-0.5 flex-shrink-0"><i className="ri-information-line text-blue-600 text-sm"></i></div>
            <p className="text-xs text-blue-700">
              <strong>Rating Scale:</strong> 1 = Needs Improvement · 2 = Meets Some Expectations · 3 = Meets Expectations · 4 = Exceeds Expectations · 5 = Outstanding
            </p>
          </div>

          {step === 'company' && (
            <div className="space-y-4">
              <div>
                <h3 className="font-semibold text-gray-800 mb-1">Company Goals</h3>
                <p className="text-xs text-gray-500">Select the company goals you contributed to and rate your performance</p>
              </div>
              {relevantCompanyGoals.map(goal => {
                const isSelected = selectedCGIds.includes(goal.id);
                const rating = cgRatings[goal.id]?.rating || 3;
                const comment = cgRatings[goal.id]?.comment || '';
                return (
                  <div key={goal.id} className={`border-2 rounded-xl p-4 transition-all`} style={isSelected ? { borderColor: '#b828a0', background: '#fdf2fb' } : { borderColor: '#f3f4f6' }}>
                    <div className="flex items-start gap-3">
                      <button
                        onClick={() => toggleCG(goal.id)}
                        className="w-5 h-5 rounded flex items-center justify-center flex-shrink-0 mt-0.5 cursor-pointer transition-all"
                        style={isSelected ? { background: '#b828a0', color: 'white' } : { border: '2px solid #d1d5db' }}
                      >
                        {isSelected && <i className="ri-check-line text-xs"></i>}
                      </button>
                      <div className="flex-1">
                        <p className="text-sm font-semibold text-gray-800">{goal.title}</p>
                        <p className="text-xs text-gray-500 mt-0.5">{goal.kra} · Target: {goal.target}</p>
                        {isSelected && (
                          <div className="mt-3 space-y-2">
                            <div>
                              <p className="text-xs font-medium text-gray-600 mb-1">Your Rating</p>
                              <div className="flex gap-2">
                                {[1, 2, 3, 4, 5].map(v => (
                                  <button
                                    key={v}
                                    onClick={() => setCGRatings(prev => ({ ...prev, [goal.id]: { ...prev[goal.id], rating: v } }))}
                                    className={`flex-1 py-2 rounded-lg text-sm font-bold cursor-pointer transition-all ${rating === v ? 'text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
                                    style={rating === v ? { background: '#b828a0' } : {}}
                                  >
                                    {v}
                                  </button>
                                ))}
                              </div>
                              <p className="text-xs text-center mt-1 font-medium" style={{ color: '#b828a0' }}>{RATING_LABELS[rating]}</p>
                            </div>
                            <div>
                              <p className="text-xs font-medium text-gray-600 mb-1">Comment (optional)</p>
                              <input
                                value={comment}
                                onChange={e => setCGRatings(prev => ({ ...prev, [goal.id]: { ...prev[goal.id], comment: e.target.value } }))}
                                placeholder="Briefly describe your contribution..."
                                className="w-full border border-gray-200 rounded-lg px-3 py-2 text-xs outline-none"
                              />
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                );
              })}
              <div className="flex justify-end pt-2">
                <button
                  onClick={() => setStep('dept')}
                  disabled={selectedCGIds.length === 0}
                  className="flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-medium text-white cursor-pointer whitespace-nowrap disabled:opacity-50"
                  style={{ background: '#b828a0' }}
                >
                  Next: Department Goals <i className="ri-arrow-right-line text-sm"></i>
                </button>
              </div>
            </div>
          )}

          {step === 'dept' && (
            <div className="space-y-4">
              <div>
                <h3 className="font-semibold text-gray-800 mb-1">Department Goals — {appraisal.dept}</h3>
                <p className="text-xs text-gray-500">Rate your performance on your department's goals</p>
              </div>
              {deptGoals.length === 0 ? (
                <div className="text-center py-8 text-gray-400 text-sm bg-gray-50 rounded-xl">
                  No department goals configured for {appraisal.dept}
                </div>
              ) : (
                deptGoals.map(goal => {
                  const isSelected = selectedDGIds.includes(goal.id);
                  const rating = dgRatings[goal.id]?.rating || 3;
                  const comment = dgRatings[goal.id]?.comment || '';
                  return (
                    <div key={goal.id} className={`border-2 rounded-xl p-4 transition-all`} style={isSelected ? { borderColor: '#b828a0', background: '#fdf2fb' } : { borderColor: '#f3f4f6' }}>
                      <div className="flex items-start gap-3">
                        <button
                          onClick={() => toggleDG(goal.id)}
                          className="w-5 h-5 rounded flex items-center justify-center flex-shrink-0 mt-0.5 cursor-pointer transition-all"
                          style={isSelected ? { background: '#b828a0', color: 'white' } : { border: '2px solid #d1d5db' }}
                        >
                          {isSelected && <i className="ri-check-line text-xs"></i>}
                        </button>
                        <div className="flex-1">
                          <p className="text-sm font-semibold text-gray-800">{goal.title}</p>
                          <p className="text-xs text-gray-500 mt-0.5">{goal.description}</p>
                          {isSelected && (
                            <div className="mt-3 space-y-2">
                              <div>
                                <p className="text-xs font-medium text-gray-600 mb-1">Your Rating</p>
                                <div className="flex gap-2">
                                  {[1, 2, 3, 4, 5].map(v => (
                                    <button
                                      key={v}
                                      onClick={() => setDGRatings(prev => ({ ...prev, [goal.id]: { ...prev[goal.id], rating: v } }))}
                                      className={`flex-1 py-2 rounded-lg text-sm font-bold cursor-pointer transition-all ${rating === v ? 'text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
                                      style={rating === v ? { background: '#b828a0' } : {}}
                                    >
                                      {v}
                                    </button>
                                  ))}
                                </div>
                                <p className="text-xs text-center mt-1 font-medium" style={{ color: '#b828a0' }}>{RATING_LABELS[rating]}</p>
                              </div>
                              <div>
                                <p className="text-xs font-medium text-gray-600 mb-1">Comment (optional)</p>
                                <input
                                  value={comment}
                                  onChange={e => setDGRatings(prev => ({ ...prev, [goal.id]: { ...prev[goal.id], comment: e.target.value } }))}
                                  placeholder="Briefly describe your contribution..."
                                  className="w-full border border-gray-200 rounded-lg px-3 py-2 text-xs outline-none"
                                />
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  );
                })
              )}
              <div className="flex justify-between pt-2">
                <button onClick={() => setStep('company')} className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">
                  <i className="ri-arrow-left-line text-sm"></i> Back
                </button>
                <button onClick={() => setStep('comments')} className="flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-medium text-white cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>
                  Next: Comments <i className="ri-arrow-right-line text-sm"></i>
                </button>
              </div>
            </div>
          )}

          {step === 'comments' && (
            <div className="space-y-4">
              <div>
                <h3 className="font-semibold text-gray-800 mb-1">Overall Self-Assessment Comments</h3>
                <p className="text-xs text-gray-500">Provide a summary of your performance, achievements, and areas for growth</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Your Comments</label>
                <textarea
                  value={comments}
                  onChange={e => setComments(e.target.value)}
                  rows={6}
                  maxLength={500}
                  placeholder="Describe your key achievements this period, challenges faced, support needed, and career aspirations..."
                  className="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm outline-none resize-none focus:ring-2 focus:ring-pink-300"
                />
                <p className="text-xs text-gray-400 text-right mt-1">{comments.length}/500</p>
              </div>
              <div className="flex justify-between pt-2">
                <button onClick={() => setStep('dept')} className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">
                  <i className="ri-arrow-left-line text-sm"></i> Back
                </button>
                <button onClick={() => setStep('review')} className="flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-medium text-white cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>
                  Review & Submit <i className="ri-arrow-right-line text-sm"></i>
                </button>
              </div>
            </div>
          )}

          {step === 'review' && (
            <div className="space-y-4">
              <div className="bg-green-50 border border-green-100 rounded-xl p-4 flex items-start gap-3">
                <div className="w-5 h-5 flex items-center justify-center mt-0.5"><i className="ri-checkbox-circle-line text-green-600 text-sm"></i></div>
                <div>
                  <p className="text-sm font-semibold text-green-800">Ready to submit</p>
                  <p className="text-xs text-green-600 mt-0.5">Once submitted, your HOD will be notified to review and approve your appraisal. You cannot edit after submission.</p>
                </div>
              </div>

              <div className="border border-gray-100 rounded-xl p-4">
                <h4 className="text-sm font-semibold text-gray-700 mb-3">Company Goals ({selectedCGIds.length} rated)</h4>
                <div className="space-y-2">
                  {selectedCGIds.map(id => {
                    const goal = COMPANY_GOALS.find(g => g.id === id);
                    const r = cgRatings[id];
                    return (
                      <div key={id} className="flex items-center justify-between">
                        <span className="text-xs text-gray-600 truncate max-w-[300px]">{goal?.title}</span>
                        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${RATING_BG[r?.rating || 3]}`}>{r?.rating || 3}/5</span>
                      </div>
                    );
                  })}
                </div>
              </div>

              {selectedDGIds.length > 0 && (
                <div className="border border-gray-100 rounded-xl p-4">
                  <h4 className="text-sm font-semibold text-gray-700 mb-3">Department Goals ({selectedDGIds.length} rated)</h4>
                  <div className="space-y-2">
                    {selectedDGIds.map(id => {
                      const goal = DEPARTMENT_GOALS.find(g => g.id === id);
                      const r = dgRatings[id];
                      return (
                        <div key={id} className="flex items-center justify-between">
                          <span className="text-xs text-gray-600 truncate max-w-[300px]">{goal?.title}</span>
                          <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${RATING_BG[r?.rating || 3]}`}>{r?.rating || 3}/5</span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              {comments && (
                <div className="border border-gray-100 rounded-xl p-4">
                  <h4 className="text-sm font-semibold text-gray-700 mb-2">Your Comments</h4>
                  <p className="text-sm text-gray-600">{comments}</p>
                </div>
              )}

              <div className="flex justify-between pt-2">
                <button onClick={() => setStep('comments')} className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">
                  <i className="ri-arrow-left-line text-sm"></i> Back
                </button>
                <button
                  onClick={handleSubmit}
                  className="flex items-center gap-2 px-6 py-2.5 rounded-xl text-sm font-semibold text-white cursor-pointer whitespace-nowrap"
                  style={{ background: '#b828a0' }}
                >
                  <div className="w-4 h-4 flex items-center justify-center"><i className="ri-send-plane-line text-sm"></i></div>
                  Submit Self-Assessment
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}