import React from 'react';
import { apiClient } from '@/shared/services/apiClient';

export default function TaskCard({ task, onClick, onTaskUpdated }) {
  // Guard check: return null safely if task prop is undefined or null
  if (!task) return null;

  const isCompleted = task.status?.toLowerCase() === 'completed';

  // Dynamic Initials Generator (e.g., "Horizon Admin" -> "HA", "John Doe" -> "JD")
  const getInitials = (name) => {
    if (!name || name === 'Unassigned') return '?';
    const parts = name.trim().split(' ').filter(Boolean);
    if (parts.length === 0) return '?';
    if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
    return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
  };

  // Dynamic Color Generator so different team members get unique avatar colors
  const getAvatarBg = (name) => {
    if (!name || name === 'Unassigned') return 'bg-slate-700';
    const colors = [
      'bg-purple-600',
      'bg-indigo-600',
      'bg-sky-600',
      'bg-emerald-600',
      'bg-amber-600',
      'bg-rose-600',
      'bg-teal-600',
    ];
    let hash = 0;
    for (let i = 0; i < name.length; i++) {
      hash = name.charCodeAt(i) + ((hash << 5) - hash);
    }
    return colors[Math.abs(hash) % colors.length];
  };

const handleClaimTask = async (e) => {
    e.stopPropagation();

    // 1. Get cached logged-in user info for instant optimistic render
    let currentUser = null;
    try {
      const stored = localStorage.getItem('user');
      if (stored) currentUser = JSON.parse(stored);
    } catch (err) {
      console.error(err);
    }

    const fallbackName = currentUser?.name || currentUser?.full_name || 'Horizon Admin';

    // 2. Trigger instant local UI update (NO REFRESH REQUIRED!)
    const updatedTask = {
      ...task,
      assignee_id: currentUser?.id || 1,
      assignee: fallbackName,
      assignee_name: fallbackName,
    };
    
    onTaskUpdated?.(updatedTask);

    // 3. Persist to SQL Server in background
    try {
      const res = await apiClient('/tasks/assign-me.php', {
        method: 'POST',
        body: { task_id: task.id },
      });

      if (res?.success && res?.user) {
        // Confirm real backend values
        onTaskUpdated?.({
          ...task,
          assignee_id: res.user.id,
          assignee: res.user.name,
          assignee_name: res.user.name,
        });
      }
    } catch (err) {
      console.error('Failed to claim task on backend:', err);
      // Revert if API request fails
      onTaskUpdated?.(task);
    }
  };

  // Extract raw assignee and normalize stale/legacy placeholders
  const rawAssignee = task.assignee_name || task.assignee || '';
  const assigneeName = (rawAssignee === 'Admin User' || rawAssignee === 'User') ? '' : rawAssignee;
  const isAssigned = Boolean(assigneeName && assigneeName !== 'Unassigned');

  return (
    <div
      onClick={() => onClick?.(task)}
      className="bg-[#1a212d] hover:bg-[#222b3a] border border-[#2d3748] hover:border-sky-500/50 rounded-xl p-3.5 shadow-md cursor-pointer transition-all group space-y-3"
    >
      {/* Task Title */}
      <div className="flex items-start justify-between gap-2">
        <h4 className={`text-xs font-semibold leading-snug ${isCompleted ? 'line-through text-slate-500' : 'text-slate-100'}`}>
          {task.title || 'Untitled Task'}
        </h4>
      </div>

      {/* Tags */}
      {task.tags && task.tags.length > 0 && (
        <div className="flex flex-wrap gap-1">
          {task.tags.map((tag) => (
            <span
              key={tag.id || tag.name}
              style={{ 
                backgroundColor: `${tag.color || '#3b82f6'}20`, 
                color: tag.color || '#3b82f6', 
                borderColor: `${tag.color || '#3b82f6'}40` 
              }}
              className="text-[10px] font-medium px-2 py-0.5 rounded-full border"
            >
              {tag.name}
            </span>
          ))}
        </div>
      )}

      {/* Bottom Bar: Dynamic Avatar Holder & Due Date */}
      <div className="flex items-center justify-between pt-2 border-t border-[#2d3748]/50 text-[11px]">
        
        {/* Dynamic Avatar */}
        <div className="flex items-center">
          {isAssigned ? (
            <div
              title={`Assigned to ${assigneeName}`}
              className={`w-6 h-6 rounded-full ${getAvatarBg(assigneeName)} text-white flex items-center justify-center font-bold text-[10px] shadow-sm border border-white/20 shrink-0`}
            >
              {getInitials(assigneeName)}
            </div>
          ) : (
            /* Asana Dashed Placeholder Circle for Unassigned Tasks */
            <button
              type="button"
              onClick={handleClaimTask}
              title="Assign to me"
              className="w-6 h-6 rounded-full border-2 border-dashed border-slate-500 hover:border-sky-400 hover:bg-sky-500/10 text-slate-400 hover:text-sky-300 flex items-center justify-center transition-all shrink-0 group/avatar"
            >
              <svg
                className="w-3 h-3 transition-transform group-hover/avatar:scale-110"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth="2"
                  d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
                />
              </svg>
            </button>
          )}
        </div>

        {/* Due Date */}
        <span className={task.due_date ? 'text-emerald-400 font-mono' : 'text-slate-500'}>
          {task.due_date || 'No due date'}
        </span>
      </div>
    </div>
  );
}