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

export interface KPIType {
  id: string;
  employeeId: string;
  title: string;
  description: string;
  targetValue: string;
  measurementMethod: string;
  frequency: 'Monthly' | 'Quarterly' | 'Annual';
  performanceScore: number;
  targetDeadline: string;
  progress: number;
  linkedWorkPlanId?: string;
}

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

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

  const circumference = 2 * Math.PI * 36;
  const offset = circumference - (form.progress / 100) * circumference;

  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.02, y: -3, boxShadow: '0 10px 32px rgba(0,0,0,0.08)' }}
        whileTap={{ scale: 0.985 }}
        className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 cursor-pointer"
      >
        <div className="flex items-start gap-4">
          <div className="relative w-20 h-20 flex-shrink-0">
            <svg className="w-20 h-20 -rotate-90" viewBox="0 0 80 80">
              <circle cx="40" cy="40" r="36" stroke="#f3f4f6" strokeWidth="8" fill="none" />
              <motion.circle
                cx="40" cy="40" r="36"
                stroke={form.progress >= 80 ? '#16a34a' : form.progress >= 50 ? '#b828a0' : '#dc2626'}
                strokeWidth="8" fill="none" strokeLinecap="round"
                strokeDasharray={circumference}
                initial={{ strokeDashoffset: circumference }}
                whileInView={{ strokeDashoffset: offset }}
                viewport={{ once: true }}
                transition={{ duration: 1, delay: 0.2 }}
              />
            </svg>
            <div className="absolute inset-0 flex items-center justify-center">
              <span className="text-sm font-bold text-gray-800">{form.progress}%</span>
            </div>
          </div>
          <div className="flex-1 min-w-0">
            <h4 className="font-semibold text-gray-800 text-sm">{form.title}</h4>
            <p className="text-xs text-gray-500 mt-0.5 line-clamp-2">{form.description}</p>
            <div className="flex items-center gap-2 mt-2 flex-wrap">
              <span className="text-xs px-2 py-0.5 rounded-full bg-purple-50 text-purple-700 font-medium">{form.frequency}</span>
              <span className="text-xs text-gray-400">Target: {form.targetValue}</span>
            </div>
            <p className="text-xs text-gray-400 mt-1">Method: {form.measurementMethod}</p>
            <p className="text-xs text-gray-400">Deadline: {form.targetDeadline}</p>
            {form.performanceScore > 0 && (
              <p className="text-xs font-semibold mt-1" style={{ color: form.performanceScore >= 4 ? '#16a34a' : form.performanceScore >= 3 ? '#b828a0' : '#dc2626' }}>
                Score: {form.performanceScore}/5
              </p>
            )}
            <button
              onClick={e => { e.stopPropagation(); setForm({ ...kpi }); setEditing(true); }}
              className="mt-2 flex items-center gap-1 text-xs px-3 py-1.5 rounded-lg text-white font-medium cursor-pointer whitespace-nowrap"
              style={{ background: '#b828a0' }}>
              <i className="ri-edit-line text-xs"></i> Update
            </button>
          </div>
        </div>
      </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: '#b828a0' }}>
              <h3 className="text-white font-bold text-base">Update KPI</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">KPI 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 className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs font-medium text-gray-600 block mb-1">Target Value</label>
                  <input value={form.targetValue} onChange={e => setForm(f => ({ ...f, targetValue: 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">Measurement Method</label>
                  <input value={form.measurementMethod} onChange={e => setForm(f => ({ ...f, measurementMethod: 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">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">Performance Score (0-5)</label>
                  <input type="number" min={0} max={5} step={0.1} value={form.performanceScore} onChange={e => setForm(f => ({ ...f, performanceScore: 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">Target Deadline</label>
                  <input type="date" value={form.targetDeadline} onChange={e => setForm(f => ({ ...f, targetDeadline: 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">Frequency</label>
                  <div className="flex gap-1">
                    {(['Monthly','Quarterly','Annual'] as const).map(fr => (
                      <button key={fr} onClick={() => setForm(f => ({ ...f, frequency: fr }))}
                        className={`flex-1 py-1.5 rounded-lg text-xs font-medium cursor-pointer border transition-all ${form.frequency === fr ? 'text-white border-transparent' : 'bg-gray-50 text-gray-600 border-gray-200'}`}
                        style={form.frequency === fr ? { background: '#b828a0' } : {}}>
                        {fr}
                      </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: '#b828a0' }}>Save Changes</button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}