'use client';
import { useState } from 'react';
import { COMPANY_GOALS, DEPARTMENT_GOALS, CompanyGoal, DepartmentGoal } from './performanceData';

const DEPT_COLORS: Record<string, string> = {
  ICT: 'bg-blue-100 text-blue-700',
  HR: 'bg-pink-100 text-pink-700',
  Finance: 'bg-green-100 text-green-700',
  Operations: 'bg-orange-100 text-orange-700',
  Communications: 'bg-purple-100 text-purple-700',
  'M&E': 'bg-teal-100 text-teal-700',
};

const KRA_ICONS: Record<string, string> = {
  'Business Development Services': 'ri-briefcase-line',
  'Youth Skills Training': 'ri-graduation-cap-line',
  'Certificate Issuance': 'ri-award-line',
  'Fund Visibility Enhancement': 'ri-megaphone-line',
  'Board Capacity Building': 'ri-team-line',
  'Monitoring & Evaluation': 'ri-bar-chart-line',
};

export default function GoalsTab() {
  const [activeView, setActiveView] = useState<'company' | 'department'>('company');
  const [deptFilter, setDeptFilter] = useState('All');
  const [expandedGoal, setExpandedGoal] = useState<string | null>(null);
  const [showAddCompany, setShowAddCompany] = useState(false);
  const [companyGoals, setCompanyGoals] = useState<CompanyGoal[]>(COMPANY_GOALS);
  const [deptGoals] = useState<DepartmentGoal[]>(DEPARTMENT_GOALS);
  const [newCG, setNewCG] = useState({ kra: '', title: '', description: '', target: '' });

  const DEPARTMENTS = ['All', 'ICT', 'HR', 'Finance', 'Operations', 'Communications', 'M&E'];

  const filteredDeptGoals = deptFilter === 'All'
    ? deptGoals
    : deptGoals.filter(g => g.department === deptFilter);

  const getAlignedGoal = (id: string) => companyGoals.find(g => g.id === id);

  const handleAddCG = () => {
    if (!newCG.title) return;
    const id = `CG${companyGoals.length + 1}`;
    setCompanyGoals(prev => [...prev, { ...newCG, id, fiscalYear: '2025-2026' }]);
    setNewCG({ kra: '', title: '', description: '', target: '' });
    setShowAddCompany(false);
  };

  return (
    <div>
      <div className="grid grid-cols-3 gap-4 mb-5">
        {[
          { label: 'Company Goals', value: companyGoals.length, icon: 'ri-building-line', color: 'bg-purple-50 text-purple-600' },
          { label: 'Department Goals', value: deptGoals.length, icon: 'ri-flag-line', color: 'bg-pink-50 text-pink-600' },
          { label: 'Fiscal Year', value: '2025-2026', icon: 'ri-calendar-line', color: 'bg-yellow-50 text-yellow-600' },
        ].map(s => (
          <div key={s.label} className="bg-white border border-gray-100 rounded-xl p-4 flex items-center gap-3 shadow-sm">
            <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${s.color}`}>
              <i className={`${s.icon} text-lg`}></i>
            </div>
            <div>
              <div className="text-xl font-bold text-gray-800">{s.value}</div>
              <div className="text-xs text-gray-500">{s.label}</div>
            </div>
          </div>
        ))}
      </div>

      <div className="bg-white border border-gray-100 rounded-xl shadow-sm mb-5">
        <div className="flex border-b border-gray-100">
          {[
            { id: 'company', label: 'Company Goals', icon: 'ri-building-line' },
            { id: 'department', label: 'Department Goals', icon: 'ri-flag-line' },
          ].map(tab => (
            <button
              key={tab.id}
              onClick={() => setActiveView(tab.id as any)}
              className={`flex items-center gap-2 px-5 py-3 text-sm font-medium border-b-2 transition-all cursor-pointer whitespace-nowrap`}
              style={activeView === tab.id ? { borderColor: '#b828a0', color: '#b828a0' } : { borderColor: 'transparent', color: '#6b7280' }}
            >
              <i className={`${tab.icon} text-sm`}></i>
              {tab.label}
            </button>
          ))}
        </div>

        <div className="p-5">
          {activeView === 'company' && (
            <div>
              <div className="flex items-center justify-between mb-4">
                <div>
                  <h3 className="font-semibold text-gray-800">Uwezo Fund Company Goals — FY 2025-2026</h3>
                  <p className="text-xs text-gray-500 mt-0.5">Strategic goals aligned to the Uwezo Fund Workplan 2025-2026 (Set by HR)</p>
                </div>
                <button
                  onClick={() => setShowAddCompany(true)}
                  className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap"
                  style={{ background: '#b828a0' }}
                >
                  <div className="w-4 h-4 flex items-center justify-center"><i className="ri-add-line text-sm"></i></div>
                  Add Goal
                </button>
              </div>

              {showAddCompany && (
                <div className="bg-gray-50 border border-gray-200 rounded-xl p-4 mb-4">
                  <h4 className="font-semibold text-gray-700 text-sm mb-3">New Company Goal</h4>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="text-xs font-medium text-gray-600 block mb-1">KRA / Strategic Area</label>
                      <input value={newCG.kra} onChange={e => setNewCG(f => ({ ...f, kra: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="e.g. Business Development" />
                    </div>
                    <div>
                      <label className="text-xs font-medium text-gray-600 block mb-1">Goal Title</label>
                      <input value={newCG.title} onChange={e => setNewCG(f => ({ ...f, title: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="Goal title" />
                    </div>
                    <div className="col-span-2">
                      <label className="text-xs font-medium text-gray-600 block mb-1">Target / Success Metric</label>
                      <input value={newCG.target} onChange={e => setNewCG(f => ({ ...f, target: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="Measurable target" />
                    </div>
                    <div className="col-span-2">
                      <label className="text-xs font-medium text-gray-600 block mb-1">Description</label>
                      <textarea value={newCG.description} onChange={e => setNewCG(f => ({ ...f, description: e.target.value }))} rows={2} maxLength={500} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none resize-none" />
                    </div>
                  </div>
                  <div className="flex gap-2 mt-3">
                    <button onClick={() => setShowAddCompany(false)} className="px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
                    <button onClick={handleAddCG} className="px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>Save Goal</button>
                  </div>
                </div>
              )}

              <div className="space-y-3">
                {companyGoals.map((goal, idx) => (
                  <div key={goal.id} className="border border-gray-100 rounded-xl overflow-hidden">
                    <div
                      className="p-4 cursor-pointer hover:bg-gray-50 transition-colors"
                      onClick={() => setExpandedGoal(expandedGoal === goal.id ? null : goal.id)}
                    >
                      <div className="flex items-start gap-3">
                        <div className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: '#fdf2fb' }}>
                          <i className={`${KRA_ICONS[goal.kra] || 'ri-flag-line'} text-base`} style={{ color: '#b828a0' }}></i>
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 mb-0.5">
                            <span className="text-xs font-semibold px-2 py-0.5 rounded-full" style={{ background: '#fdf2fb', color: '#b828a0' }}>{goal.kra}</span>
                            <span className="text-xs text-gray-400">{goal.id}</span>
                          </div>
                          <p className="text-sm font-semibold text-gray-800">{goal.title}</p>
                          <p className="text-xs text-gray-500 mt-0.5 truncate">{goal.target}</p>
                        </div>
                        <div className="flex items-center gap-2 flex-shrink-0">
                          <span className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full">{goal.fiscalYear}</span>
                          <div className="w-4 h-4 flex items-center justify-center">
                            <i className={`${expandedGoal === goal.id ? 'ri-arrow-up-s-line' : 'ri-arrow-down-s-line'} text-gray-400`}></i>
                          </div>
                        </div>
                      </div>
                    </div>
                    {expandedGoal === goal.id && (
                      <div className="border-t border-gray-100 px-4 pb-4 pt-3 bg-gray-50">
                        <p className="text-sm text-gray-600 mb-2">{goal.description}</p>
                        <div className="flex items-center gap-2">
                          <div className="w-4 h-4 flex items-center justify-center"><i className="ri-focus-3-line text-green-600 text-sm"></i></div>
                          <span className="text-xs font-semibold text-gray-700">Target:</span>
                          <span className="text-xs text-gray-600">{goal.target}</span>
                        </div>
                        <div className="mt-3">
                          <p className="text-xs font-semibold text-gray-500 mb-1">Aligned Department Goals:</p>
                          <div className="flex flex-wrap gap-1">
                            {deptGoals.filter(dg => dg.alignedToCompanyGoalId === goal.id).map(dg => (
                              <span key={dg.id} className={`text-xs px-2 py-0.5 rounded-full font-medium ${DEPT_COLORS[dg.department] || 'bg-gray-100 text-gray-600'}`}>
                                {dg.department}: {dg.title.slice(0, 40)}...
                              </span>
                            ))}
                            {deptGoals.filter(dg => dg.alignedToCompanyGoalId === goal.id).length === 0 && (
                              <span className="text-xs text-gray-400">No department goals aligned yet</span>
                            )}
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}

          {activeView === 'department' && (
            <div>
              <div className="flex items-center justify-between mb-4">
                <div>
                  <h3 className="font-semibold text-gray-800">Department Goals — FY 2025-2026</h3>
                  <p className="text-xs text-gray-500 mt-0.5">Goals aligned to company strategic objectives by department (Set by HODs only)</p>
                </div>
                <div className="flex items-center gap-2">
                  <div className="flex gap-1">
                    {DEPARTMENTS.map(d => (
                      <button
                        key={d}
                        onClick={() => setDeptFilter(d)}
                        className={`px-3 py-1.5 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap transition-all ${deptFilter === d ? 'text-white' : 'bg-gray-100 text-gray-600'}`}
                        style={deptFilter === d ? { background: '#b828a0' } : {}}
                      >
                        {d}
                      </button>
                    ))}
                  </div>
                </div>
              </div>

              <div className="bg-amber-50 border border-amber-200 rounded-xl px-4 py-3 mb-4 flex items-start gap-2">
                <i className="ri-information-line text-amber-600 mt-0.5 text-sm"></i>
                <p className="text-xs text-amber-800">
                  <strong>Note:</strong> Department goals can only be added by HODs from their respective HOD portals. 
                  HR can view all department goals but cannot add or edit them.
                </p>
              </div>

              <div className="space-y-3">
                {filteredDeptGoals.map(goal => {
                  const aligned = getAlignedGoal(goal.alignedToCompanyGoalId);
                  return (
                    <div key={goal.id} className="border border-gray-100 rounded-xl p-4 hover:border-pink-200 transition-colors">
                      <div className="flex items-start gap-3">
                        <div className={`px-2 py-0.5 rounded-full text-xs font-semibold flex-shrink-0 mt-0.5 ${DEPT_COLORS[goal.department] || 'bg-gray-100 text-gray-600'}`}>
                          {goal.department}
                        </div>
                        <div className="flex-1 min-w-0">
                          <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>
                          {aligned && (
                            <div className="flex items-center gap-1.5 mt-2">
                              <div className="w-3 h-3 flex items-center justify-center"><i className="ri-links-line text-xs" style={{ color: '#b828a0' }}></i></div>
                              <span className="text-xs text-gray-400">Aligned to:</span>
                              <span className="text-xs font-medium" style={{ color: '#b828a0' }}>{aligned.kra}</span>
                            </div>
                          )}
                        </div>
                        <span className="text-xs text-gray-400 flex-shrink-0">{goal.id}</span>
                      </div>
                    </div>
                  );
                })}
                {filteredDeptGoals.length === 0 && (
                  <div className="text-center py-8 text-gray-400 text-sm">No department goals found</div>
                )}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
