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

interface DeptTarget {
  id: string;
  title: string;
  description: string;
  quarter: string;
  expectedOutcomes: string;
  deadline: string;
  priority: 'High' | 'Medium' | 'Low';
  measurableObjectives: string;
  progress: number;
  status: 'Pending' | 'Ongoing' | 'Completed' | 'Delayed';
}

const statusConfig: Record<string, { bg: string; text: string; border: string }> = {
  Pending: { bg: 'bg-gray-50', text: 'text-gray-600', border: 'border-gray-200' },
  Ongoing: { bg: 'bg-blue-50', text: 'text-blue-700', border: 'border-blue-200' },
  Completed: { bg: 'bg-green-50', text: 'text-green-700', border: 'border-green-200' },
  Delayed: { bg: 'bg-red-50', text: 'text-red-700', border: 'border-red-200' },
};

const priorityConfig: Record<string, { bg: string; text: string }> = {
  High: { bg: 'bg-red-100', text: 'text-red-700' },
  Medium: { bg: 'bg-amber-100', text: 'text-amber-700' },
  Low: { bg: 'bg-gray-100', text: 'text-gray-600' },
};

interface Props {
  target: DeptTarget;
  index: number;
  onUpdate?: (updated: DeptTarget) => void;
}

export default function DeptTargetCard({ target, index, onUpdate }: Props) {
  const [editing, setEditing] = useState(false);
  const [form, setForm] = useState<DeptTarget>({ ...target });

  const st = statusConfig[form.status];
  const pr = priorityConfig[form.priority];

  const handleSave = () => {
    onUpdate?.(form);
    setEditing(false);
  };

  return (
    <>
      <motion.div
        initial={{ opacity: 0, y: 16 }}
        whileInView={{ opacity: 1, y: 0 }}
        viewport={{ once: true }}
        transition={{ duration: 0.35, delay: index * 0.08 }}
        whileHover={{ scale: 1.015, y: -3, boxShadow: '0 10px 32px rgba(0,0,0,0.08)' }}
        whileTap={{ scale: 0.985 }}
        className={`bg-white rounded-2xl border ${st.border} shadow-sm p-5 cursor-pointer`}
      >
        <div className="flex items-start justify-between mb-3">
          <div className="flex-1 pr-3">
            <div className="flex items-center gap-2 mb-1.5 flex-wrap">
              <span className={`text-xs font-semibold px-2.5 py-0.5 rounded-full ${pr.bg} ${pr.text}`}>{form.priority} Priority</span>
              <span className="text-xs font-semibold px-2.5 py-0.5 rounded-full bg-purple-100 text-purple-700">{form.quarter}</span>
              <span className={`text-xs font-semibold px-2.5 py-0.5 rounded-full ${st.bg} ${st.text}`}>{form.status}</span>
            </div>
            <h4 className="font-semibold text-gray-800 text-sm">{form.title}</h4>
            <p className="text-xs text-gray-500 mt-1 line-clamp-2">{form.description}</p>
          </div>
          <div className="text-right flex-shrink-0">
            <p className="text-xs text-gray-400">Due</p>
            <p className="text-xs font-semibold text-gray-700">{form.deadline}</p>
          </div>
        </div>

        <div className="mb-3">
          <p className="text-xs font-medium text-gray-500 mb-1">Measurable Objectives</p>
          <p className="text-xs text-gray-600 bg-gray-50 rounded-lg px-3 py-2">{form.measurableObjectives}</p>
        </div>

        <div className="mb-2">
          <p className="text-xs font-medium text-gray-500 mb-1">Expected Outcomes</p>
          <p className="text-xs text-gray-600">{form.expectedOutcomes}</p>
        </div>

        <div className="flex items-center gap-3 mt-3">
          <div className="flex-1 bg-gray-100 rounded-full h-2.5">
            <motion.div initial={{ width: 0 }} whileInView={{ width: `${form.progress}%` }} viewport={{ once: true }} transition={{ duration: 0.8, delay: 0.2 }}
              className="h-2.5 rounded-full"
              style={{ background: form.status === 'Delayed' ? '#dc2626' : form.status === 'Completed' ? '#16a34a' : '#b828a0' }} />
          </div>
          <span className="text-xs font-bold text-gray-700 w-10 text-right">{form.progress}%</span>
        </div>

        <button onClick={e => { e.stopPropagation(); setForm({ ...target }); setEditing(true); }}
          className="mt-3 flex items-center gap-1 text-xs px-3 py-1.5 rounded-lg text-white font-medium cursor-pointer whitespace-nowrap"
          style={{ background: '#B22698' }}>
          <i className="ri-edit-line text-xs"></i> Update
        </button>
      </motion.div>

      {editing && (
        <div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md max-h-[90vh] overflow-y-auto">
            <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: '#B22698' }}>
              <h3 className="text-white font-bold text-base">Update Departmental Target</h3>
              <button onClick={() => setEditing(false)} className="w-7 h-7 flex items-center justify-center cursor-pointer">
                <i className="ri-close-line text-white text-lg"></i>
              </button>
            </div>
            <div className="p-5 space-y-3">
              <div>
                <label className="text-xs font-medium text-gray-600 block mb-1">Title</label>
                <input value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
              </div>
              <div>
                <label className="text-xs font-medium text-gray-600 block mb-1">Description</label>
                <textarea value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))} rows={2} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none resize-none" />
              </div>
              <div>
                <label className="text-xs font-medium text-gray-600 block mb-1">Expected Outcomes</label>
                <input value={form.expectedOutcomes} onChange={e => setForm(f => ({ ...f, expectedOutcomes: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
              </div>
              <div>
                <label className="text-xs font-medium text-gray-600 block mb-1">Measurable Objectives</label>
                <textarea value={form.measurableObjectives} onChange={e => setForm(f => ({ ...f, measurableObjectives: e.target.value }))} rows={2} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none resize-none" />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs font-medium text-gray-600 block mb-1">Progress (%)</label>
                  <input type="number" min={0} max={100} value={form.progress} onChange={e => setForm(f => ({ ...f, progress: Math.min(100, Math.max(0, Number(e.target.value))) }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
                </div>
                <div>
                  <label className="text-xs font-medium text-gray-600 block mb-1">Deadline</label>
                  <input type="date" value={form.deadline} onChange={e => setForm(f => ({ ...f, deadline: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
                </div>
                <div>
                  <label className="text-xs font-medium text-gray-600 block mb-1">Quarter</label>
                  <div className="flex gap-1">
                    {['Q1','Q2','Q3','Q4'].map(q => (
                      <button key={q} onClick={() => setForm(f => ({ ...f, quarter: q }))}
                        className={`flex-1 py-1.5 rounded-lg text-xs font-medium cursor-pointer border ${form.quarter === q ? 'text-white border-transparent' : 'bg-gray-50 text-gray-600 border-gray-200'}`}
                        style={form.quarter === q ? { background: '#B22698' } : {}}>{q}</button>
                    ))}
                  </div>
                </div>
                <div>
                  <label className="text-xs font-medium text-gray-600 block mb-1">Status</label>
                  <div className="grid grid-cols-2 gap-1">
                    {(['Pending','Ongoing','Completed','Delayed'] as const).map(s => (
                      <button key={s} onClick={() => setForm(f => ({ ...f, status: s }))}
                        className={`py-1 rounded-lg text-xs font-medium cursor-pointer border ${form.status === s ? 'text-white border-transparent' : 'bg-gray-50 text-gray-600 border-gray-200'}`}
                        style={form.status === s ? { background: '#B22698' } : {}}>{s}</button>
                    ))}
                  </div>
                </div>
                <div className="col-span-2">
                  <label className="text-xs font-medium text-gray-600 block mb-1">Priority</label>
                  <div className="flex gap-1">
                    {(['High','Medium','Low'] as const).map(p => (
                      <button key={p} onClick={() => setForm(f => ({ ...f, priority: p }))}
                        className={`flex-1 py-1.5 rounded-lg text-xs font-medium cursor-pointer border ${form.priority === p ? 'text-white border-transparent' : 'bg-gray-50 text-gray-600 border-gray-200'}`}
                        style={form.priority === p ? { background: '#B22698' } : {}}>{p}</button>
                    ))}
                  </div>
                </div>
              </div>
              <div className="flex gap-2 pt-2">
                <button onClick={() => setEditing(false)} className="flex-1 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
                <button onClick={handleSave} className="flex-1 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#B22698' }}>Save Changes</button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}