'use client';
import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';

export interface WorkPlanTask {
  id: string;
  title: string;
  objective: string;
  expectedOutput: string;
  startDate: string;
  endDate: string;
  status: 'Not Started' | 'In Progress' | 'Completed';
  remarks: string;
  weeklyProgress: { week: number; progress: number; notes: string }[];
}

export interface WorkPlan {
  id: string;
  employeeId: string;
  objective: string;
  target: string;
  progress: number;
  dueDate: string;
  status: 'Not Started' | 'In Progress' | 'Completed';
  linkedTargetId: string;
  tasks: WorkPlanTask[] | string;
}

const taskStatusColor = (s: string) =>
  s === 'Completed' ? 'bg-green-100 text-green-700' : s === 'In Progress' ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-600';

interface WorkPlanCardProps {
  plan: WorkPlan;
  deptTargetTitle?: string;
  onAddTask?: (planId: string) => void;
  onUpdateProgress?: (planId: string, week: number, progress: number, notes: string) => void;
  onUpdate?: (updated: WorkPlan) => void;
}

export default function WorkPlanCard({ plan, deptTargetTitle, onAddTask, onUpdateProgress, onUpdate }: WorkPlanCardProps) {
  const [expanded, setExpanded] = useState(false);
  const [showWeeklyUpdate, setShowWeeklyUpdate] = useState(false);
  const [weekNum, setWeekNum] = useState(1);
  const [weekProgress, setWeekProgress] = useState(0);
  const [weekNotes, setWeekNotes] = useState('');
  
  const [editingStatus, setEditingStatus] = useState(false);
  const [tempStatus, setTempStatus] = useState(plan.status);

  // Parse tasks if it's a string, otherwise use as array
  const tasksArray = Array.isArray(plan.tasks) 
    ? plan.tasks 
    : (typeof plan.tasks === 'string' ? JSON.parse(plan.tasks || '[]') : []);
  
  const completedTasks = tasksArray.filter((t: WorkPlanTask) => t.status === 'Completed').length;

  const handleStatusChange = (newStatus: WorkPlan['status']) => {
    setTempStatus(newStatus);
    onUpdate?.({ ...plan, status: newStatus });
    setEditingStatus(false);
  };

  const handleProgressClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    setShowWeeklyUpdate(true);
  };

  const handleWeeklyUpdateSubmit = () => {
    if (weekProgress > 0) {
      onUpdateProgress?.(plan.id, weekNum, weekProgress, weekNotes);
      setShowWeeklyUpdate(false);
      setWeekNotes('');
      setWeekProgress(0);
      setWeekNum(1);
    }
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 16 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true }}
      transition={{ duration: 0.35 }}
      whileHover={{ scale: 1.01, y: -2, boxShadow: '0 8px 24px rgba(0,0,0,0.06)' }}
      className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden"
    >
      <div className="p-5 cursor-pointer" onClick={() => setExpanded(!expanded)}>
        <div className="flex items-start justify-between mb-3">
          <div className="flex-1 pr-3">
            <p className="font-semibold text-gray-800 text-sm">{plan.objective}</p>
            {deptTargetTitle && (
              <p className="text-xs text-purple-600 mt-0.5">Linked to: {deptTargetTitle}</p>
            )}
            <p className="text-xs text-gray-400 mt-1">Target: {plan.target} · Due: {plan.dueDate}</p>
            <p className="text-xs text-gray-400">{tasksArray.length} task{tasksArray.length !== 1 ? 's' : ''} · {completedTasks} completed</p>
          </div>
          <div className="flex items-center gap-2 flex-shrink-0">
            {editingStatus ? (
              <select
                value={tempStatus}
                onChange={(e) => handleStatusChange(e.target.value as WorkPlan['status'])}
                onBlur={() => setEditingStatus(false)}
                autoFocus
                className="text-xs px-2.5 py-1 rounded-full font-semibold whitespace-nowrap border-2 border-purple-500 outline-none cursor-pointer bg-white"
                style={{ color: tempStatus === 'Completed' ? '#16a34a' : tempStatus === 'In Progress' ? '#2563eb' : '#6b7280' }}
                onClick={(e) => e.stopPropagation()}
              >
                <option value="Not Started">Not Started</option>
                <option value="In Progress">In Progress</option>
                <option value="Completed">Completed</option>
              </select>
            ) : (
              <button
                onClick={(e) => { e.stopPropagation(); setEditingStatus(true); setTempStatus(plan.status); }}
                className={`text-xs px-2.5 py-1 rounded-full font-semibold whitespace-nowrap cursor-pointer transition-all hover:opacity-80 ${plan.status === 'Completed' ? 'bg-green-100 text-green-700' : plan.status === 'In Progress' ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-600'}`}
              >
                {plan.status}
                <i className="ri-arrow-down-s-line ml-1 text-xs"></i>
              </button>
            )}
            <div className="w-5 h-5 flex items-center justify-center">
              <i className={`${expanded ? 'ri-arrow-up-s-line' : 'ri-arrow-down-s-line'} text-gray-400 text-lg`}></i>
            </div>
          </div>
        </div>
        
        <div className="flex items-center gap-3">
          <div 
            className="flex-1 bg-gray-100 rounded-full h-2 cursor-pointer relative group"
            onClick={handleProgressClick}
          >
            <motion.div
              initial={{ width: 0 }}
              animate={{ width: `${plan.progress}%` }}
              transition={{ duration: 0.5 }}
              className="h-2 rounded-full"
              style={{ background: plan.status === 'Completed' ? '#16a34a' : '#b828a0' }}
            />
            <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
              <div className="bg-black/50 text-white text-[10px] px-2 py-0.5 rounded-full whitespace-nowrap">Click to update</div>
            </div>
          </div>
          <button
            onClick={handleProgressClick}
            className="text-xs font-bold text-gray-700 w-10 text-right cursor-pointer hover:text-purple-600 transition-colors"
          >
            {plan.progress}%
          </button>
        </div>
      </div>

      <AnimatePresence>
        {expanded && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.3 }}
            className="border-t border-gray-100 overflow-hidden"
          >
            <div className="p-5 space-y-4">
              {tasksArray.length > 0 && (
                <div>
                  <p className="text-xs font-semibold text-gray-600 mb-2">Tasks / Activities</p>
                  <div className="space-y-2">
                    {tasksArray.map((task: WorkPlanTask) => (
                      <div key={task.id} className="bg-gray-50 rounded-xl p-3">
                        <div className="flex items-start justify-between mb-1">
                          <div>
                            <p className="text-sm font-medium text-gray-800">{task.title}</p>
                            <p className="text-xs text-gray-500">{task.objective}</p>
                          </div>
                          <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${taskStatusColor(task.status)}`}>
                            {task.status}
                          </span>
                        </div>
                        <p className="text-xs text-gray-500 mt-1">Output: {task.expectedOutput}</p>
                        <p className="text-xs text-gray-400">{task.startDate} → {task.endDate}</p>
                        {task.remarks && <p className="text-xs text-gray-500 mt-1 italic">"{task.remarks}"</p>}
                        
                        {task.weeklyProgress && task.weeklyProgress.length > 0 && (
                          <div className="mt-2 space-y-1">
                            <p className="text-xs font-medium text-gray-600">Weekly Progress:</p>
                            {task.weeklyProgress.map((wp: { week: number; progress: number; notes: string }, idx: number) => (
                              <div key={idx} className="flex items-center gap-2 text-xs">
                                <span className="font-medium text-gray-600 w-8">W{wp.week}:</span>
                                <div className="flex-1 bg-gray-200 rounded-full h-1.5 max-w-[120px]">
                                  <div className="h-1.5 rounded-full bg-purple-500" style={{ width: `${wp.progress}%` }}></div>
                                </div>
                                <span className="text-gray-500 w-10">{wp.progress}%</span>
                                <span className="text-gray-400 truncate max-w-[200px]">{wp.notes}</span>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {showWeeklyUpdate && (
                <div className="bg-blue-50 border border-blue-200 rounded-xl p-3">
                  <p className="text-xs font-semibold text-blue-800 mb-2">Weekly Progress Update</p>
                  <div className="grid grid-cols-2 gap-2 mb-2">
                    <div>
                      <label className="text-xs text-gray-600 block mb-0.5">Week Number</label>
                      <input 
                        type="number" 
                        min={1} 
                        value={weekNum} 
                        onChange={e => setWeekNum(Number(e.target.value))} 
                        className="w-full border border-gray-200 rounded-lg px-2 py-1.5 text-xs outline-none focus:ring-2 focus:ring-purple-300" 
                      />
                    </div>
                    <div>
                      <label className="text-xs text-gray-600 block mb-0.5">Progress (%)</label>
                      <input 
                        type="number" 
                        min={0} 
                        max={100} 
                        value={weekProgress} 
                        onChange={e => setWeekProgress(Number(e.target.value))} 
                        className="w-full border border-gray-200 rounded-lg px-2 py-1.5 text-xs outline-none focus:ring-2 focus:ring-purple-300" 
                      />
                    </div>
                  </div>
                  <div className="mb-2">
                    <label className="text-xs text-gray-600 block mb-0.5">Notes / Achievements</label>
                    <textarea 
                      value={weekNotes} 
                      onChange={e => setWeekNotes(e.target.value)} 
                      rows={2} 
                      maxLength={200} 
                      className="w-full border border-gray-200 rounded-lg px-2 py-1.5 text-xs outline-none resize-none focus:ring-2 focus:ring-purple-300" 
                      placeholder="What did you accomplish this week?"
                    />
                  </div>
                  <div className="flex gap-2">
                    <button 
                      onClick={() => setShowWeeklyUpdate(false)} 
                      className="px-3 py-1.5 border border-gray-200 rounded-lg text-xs text-gray-600 cursor-pointer whitespace-nowrap hover:bg-gray-50 transition-colors"
                    >
                      Cancel
                    </button>
                    <button 
                      onClick={handleWeeklyUpdateSubmit} 
                      className="px-3 py-1.5 rounded-lg text-xs font-medium text-white cursor-pointer whitespace-nowrap hover:opacity-90 transition-opacity"
                      style={{ background: '#b828a0' }}
                    >
                      Save Update
                    </button>
                  </div>
                </div>
              )}

              <div className="flex gap-2 flex-wrap">
                <button 
                  onClick={(e) => { e.stopPropagation(); onAddTask?.(plan.id); }} 
                  className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-gray-200 text-xs text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap transition-colors"
                >
                  <i className="ri-add-line text-xs"></i>
                  Add Task
                </button>
                <button 
                  onClick={(e) => { e.stopPropagation(); setShowWeeklyUpdate(true); }} 
                  className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-gray-200 text-xs text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap transition-colors"
                >
                  <i className="ri-line-chart-line text-xs"></i>
                  Weekly Update
                </button>
              </div>

              {plan.progress > 0 && (
                <div className="bg-purple-50 rounded-lg p-3">
                  <p className="text-xs font-semibold text-purple-800 mb-1">Progress Summary</p>
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-purple-600">Overall Completion</span>
                    <span className="text-sm font-bold text-purple-700">{plan.progress}%</span>
                  </div>
                  <div className="w-full bg-purple-200 rounded-full h-1.5 mt-1">
                    <div className="h-1.5 rounded-full bg-purple-600" style={{ width: `${plan.progress}%` }}></div>
                  </div>
                  {plan.status === 'Completed' && (
                    <p className="text-xs text-green-600 mt-2 flex items-center gap-1">
                      <i className="ri-checkbox-circle-line"></i> Work plan completed!
                    </p>
                  )}
                </div>
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.div>
  );
}