import React, { useState, useEffect } from 'react';
import { taskService } from '@/shared/services/taskService';
import { apiClient } from '@/shared/services/apiClient';
import { useToast } from '@/shared/components/ui/Toast';

// Base API URL for uploads (adjust host/port if Apache/XAMPP runs on custom configuration)
const BACKEND_URL = 'http://localhost/HZ-ProjectHub-v2/backend';

export default function TaskInspector({ isOpen, onClose, task, sections = [], onTaskUpdated }) {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [dueDate, setDueDate] = useState('');
  const [assignee, setAssignee] = useState('');
  const [priority, setPriority] = useState('-');
  const [status, setStatus] = useState('-');
  const [sectionId, setSectionId] = useState('');
  const [isCompleted, setIsCompleted] = useState(false);
  const [estimatedTime, setEstimatedTime] = useState('');
  const [actualTime, setActualTime] = useState('');

  // Subtask & Comment State
  const [subtasks, setSubtasks] = useState([]);
  const [newSubtaskTitle, setNewSubtaskTitle] = useState('');
  const [comments, setComments] = useState([]);
  const [commentText, setCommentText] = useState('');
  const [screenshotPreview, setScreenshotPreview] = useState(null);
  const [isAddingComment, setIsAddingComment] = useState(false);

  const { addToast } = useToast() || {};

  // Fetch Subtasks and Comments when task changes
  useEffect(() => {
    if (task) {
      setTitle(task.title || '');
      setDescription(task.description || '');
      setDueDate(task.due_date && task.due_date !== 'No due date' ? task.due_date : '');
      setAssignee(task.assignee || 'Khyn Alfiler');
      setPriority(task.priority || '-');
      setStatus(task.status || '-');
      setSectionId(task.section_id || '');
      setIsCompleted(task.status?.toLowerCase() === 'completed' || Boolean(task.is_completed));
      setEstimatedTime(task.estimated_time || '');
      setActualTime(task.actual_time || '');
      setScreenshotPreview(null);
      setCommentText('');

      // Load Subtasks
      apiClient(`/subtasks/list.php?task_id=${task.id}`)
        .then((data) => setSubtasks(Array.isArray(data) ? data : []))
        .catch(() => setSubtasks([]));

      // Load Comments
      apiClient(`/comments/list.php?task_id=${task.id}`)
        .then((data) => setComments(Array.isArray(data) ? data : []))
        .catch(() => setComments([]));
    }
  }, [task]);

  if (!isOpen || !task) return null;

  const handleUpdateField = async (field, value) => {
    const updatedPayload = { [field]: value };

    if (field === 'title') setTitle(value);
    if (field === 'description') setDescription(value);
    if (field === 'due_date') setDueDate(value);
    if (field === 'assignee') setAssignee(value);
    if (field === 'priority') setPriority(value);
    if (field === 'status') setStatus(value);
    if (field === 'section_id') setSectionId(value);

    try {
      await taskService.updateTask(task.id, updatedPayload);
      onTaskUpdated?.({ ...task, ...updatedPayload });
    } catch (err) {
      console.error('Failed to update field:', err);
      addToast?.('Failed to auto-save field', 'error');
    }
  };

  const toggleComplete = async () => {
    const newStatus = isCompleted ? 'In Progress' : 'Completed';
    setIsCompleted(!isCompleted);
    handleUpdateField('status', newStatus);
    addToast?.(isCompleted ? 'Task marked incomplete' : 'Task completed! 🎉', 'success');
  };

  const handleClaimTask = async () => {
    try {
      const res = await apiClient('/tasks/assign-me.php', {
        method: 'POST',
        body: { task_id: task.id },
      });

      if (res?.success) {
        setAssignee(res.assignee);
        onTaskUpdated?.({ ...task, assignee: res.assignee });
        addToast?.(`Task claimed by ${res.assignee}! 🎯`, 'success');
      }
    } catch (err) {
      console.error('Failed to claim task:', err);
      addToast?.('Failed to claim task', 'error');
    }
  };

  const handleAddSubtask = async (e) => {
    e?.preventDefault();
    if (!newSubtaskTitle.trim()) return;

    try {
      const res = await apiClient('/subtasks/create.php', {
        method: 'POST',
        body: { task_id: task.id, title: newSubtaskTitle.trim() }
      });
      if (res?.subtask) {
        setSubtasks((prev) => [...prev, res.subtask]);
        setNewSubtaskTitle('');
      }
    } catch (err) {
      console.error('Failed to add subtask:', err);
      addToast?.('Failed to add subtask', 'error');
    }
  };

  // Helper to handle Pasting Screenshots (Ctrl+V) directly into the textarea
  const handlePasteScreenshot = (e) => {
    const items = e.clipboardData?.items;
    if (!items) return;

    for (let item of items) {
      if (item.type.indexOf('image') !== -1) {
        const file = item.getAsFile();
        const reader = new FileReader();
        reader.onload = (uploadEvent) => {
          setScreenshotPreview(uploadEvent.target.result); // Base64 image
        };
        reader.readAsDataURL(file);
      }
    }
  };

  // Helper to handle File Selection from disk
  const handleFileSelect = (e) => {
    const file = e.target.files?.[0];
    if (file && file.type.startsWith('image/')) {
      const reader = new FileReader();
      reader.onload = (uploadEvent) => {
        setScreenshotPreview(uploadEvent.target.result);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleAddComment = async (e) => {
    e?.preventDefault();
    if (!commentText.trim() && !screenshotPreview) return;

    try {
      setIsAddingComment(true);
      const res = await apiClient('/comments/create.php', {
        method: 'POST',
        body: {
          task_id: task.id,
          comment: commentText.trim(),
          attachment_url: screenshotPreview,
        },
      });

      if (res?.comment) {
        setComments((prev) => [...prev, res.comment]);
        setCommentText('');
        setScreenshotPreview(null);
      }
    } catch (err) {
      console.error('Failed to post comment:', err);
      addToast?.('Failed to post comment', 'error');
    } finally {
      setIsAddingComment(false);
    }
  };

  // Helper to render comment text & embedded screenshots
  const renderCommentContent = (text) => {
    if (!text) return null;

    const imgRegex = /\[IMAGE\](.*?)\[\/IMAGE\]/s;
    const match = text.match(imgRegex);

    if (match) {
      const cleanText = text.replace(imgRegex, '').trim();
      let imageUrl = match[1];

      // Convert relative backend path to absolute URL for Vite host if needed
      if (imageUrl.startsWith('/uploads/')) {
        imageUrl = `${BACKEND_URL}${imageUrl}`;
      }

      return (
        <div className="space-y-2 mt-1">
          {cleanText && <p className="text-slate-300 whitespace-pre-wrap">{cleanText}</p>}
          
          <div className="relative group inline-block">
            <img
              src={imageUrl}
              alt="Screenshot attachment"
              className="rounded-xl max-h-64 max-w-full border border-slate-700/80 shadow-lg object-contain bg-slate-950 cursor-pointer hover:border-sky-500 transition-all"
              onClick={() => window.open(imageUrl, '_blank')}
            />
          </div>
        </div>
      );
    }

    return <p className="text-slate-300 whitespace-pre-wrap">{text}</p>;
  };

  return (
    <div className="fixed top-14 right-0 bottom-0 w-full sm:w-[560px] md:w-[620px] bg-[#1a212d] border-l border-[#2d3748] shadow-2xl z-40 flex flex-col transition-all duration-300 text-slate-200">
      
      {/* 1. Asana Top Bar with Mark Complete & Mine Task */}
      <div className="px-4 py-2.5 border-b border-[#2d3748] flex items-center justify-between bg-[#161c24] shrink-0">
        <div className="flex items-center gap-2">
          <button
            onClick={toggleComplete}
            className={`flex items-center gap-1.5 px-3 py-1 rounded-lg text-xs font-medium border transition-all ${
              isCompleted
                ? 'bg-emerald-500/20 border-emerald-500 text-emerald-300'
                : 'bg-slate-800 hover:bg-slate-700 border-slate-700 text-slate-200'
            }`}
          >
            <span>{isCompleted ? '✓ Completed' : '✓ Mark complete'}</span>
          </button>

          {/* Mine this Task Button */}
          <button
            onClick={handleClaimTask}
            className="flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-medium bg-sky-950 hover:bg-sky-900 border border-sky-700/60 text-sky-300 transition-all"
            title="Assign this task to me"
          >
            <span>👤</span> Mine task
          </button>
        </div>

        <div className="flex items-center gap-3 text-slate-400 text-xs">
          <button onClick={onClose} className="hover:text-white p-1 text-sm font-bold">
            →
          </button>
        </div>
      </div>

      {/* 2. Scroll Canvas */}
      <div className="flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar">
        
        {/* Title */}
        <textarea
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          onBlur={(e) => handleUpdateField('title', e.target.value)}
          rows={2}
          className="w-full bg-transparent text-xl font-bold text-slate-100 placeholder-slate-500 resize-none focus:outline-none focus:ring-1 focus:ring-sky-500/50 rounded-lg p-1 transition-all leading-snug"
          placeholder="Task title..."
        />

        {/* Asana Field Grid */}
        <div className="space-y-2 text-xs border-y border-[#2d3748]/60 py-4">
          <div className="grid grid-cols-12 items-center min-h-[32px]">
            <span className="col-span-4 text-slate-400 font-medium">Assignee</span>
            <div className="col-span-8">
              <input
                type="text"
                value={assignee}
                onChange={(e) => setAssignee(e.target.value)}
                onBlur={(e) => handleUpdateField('assignee', e.target.value)}
                className="bg-transparent text-slate-200 focus:bg-slate-800/80 px-2 py-1 rounded-md border border-transparent focus:border-slate-700 outline-none w-full"
              />
            </div>
          </div>

          <div className="grid grid-cols-12 items-center min-h-[32px]">
            <span className="col-span-4 text-slate-400 font-medium">Due date</span>
            <div className="col-span-8">
              <input
                type="date"
                value={dueDate}
                onChange={(e) => handleUpdateField('due_date', e.target.value)}
                className="bg-transparent text-emerald-400 focus:bg-slate-800 px-2 py-1 rounded-md border border-transparent focus:border-slate-700 outline-none cursor-pointer text-xs"
              />
            </div>
          </div>

          <div className="grid grid-cols-12 items-center min-h-[32px]">
            <span className="col-span-4 text-slate-400 font-medium">Section</span>
            <div className="col-span-8">
              <select
                value={sectionId}
                onChange={(e) => handleUpdateField('section_id', e.target.value)}
                className="bg-slate-800/80 text-slate-200 border border-slate-700 rounded-md px-2 py-1 outline-none text-xs w-full"
              >
                {sections.map((sec) => (
                  <option key={sec.id} value={sec.id}>
                    {sec.name}
                  </option>
                ))}
              </select>
            </div>
          </div>
        </div>

        {/* Subtasks Section */}
        <div className="space-y-3">
          <label className="text-xs font-semibold text-slate-300 block">Subtasks</label>

          <form onSubmit={handleAddSubtask} className="flex gap-2">
            <input
              type="text"
              placeholder="+ Add subtask"
              value={newSubtaskTitle}
              onChange={(e) => setNewSubtaskTitle(e.target.value)}
              className="flex-1 bg-slate-900/50 border border-slate-800 rounded-lg px-3 py-1.5 text-xs text-slate-100 placeholder-slate-500 outline-none focus:border-sky-500"
            />
            <button
              type="submit"
              disabled={!newSubtaskTitle.trim()}
              className="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 disabled:opacity-50 text-xs text-slate-200 rounded-lg"
            >
              Add
            </button>
          </form>

          <div className="space-y-1">
            {subtasks.map((st) => (
              <div key={st.id} className="flex items-center gap-2 p-2 rounded-lg bg-slate-900/30 border border-slate-800/60 text-xs">
                <input type="checkbox" checked={st.is_completed} readOnly className="rounded" />
                <span className={st.is_completed ? 'line-through text-slate-500' : 'text-slate-200'}>
                  {st.title}
                </span>
              </div>
            ))}
          </div>
        </div>

        {/* Description Block */}
        <div className="space-y-2">
          <label className="text-xs font-semibold text-slate-300 block">Description</label>
          <textarea
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            onBlur={(e) => handleUpdateField('description', e.target.value)}
            rows={4}
            className="w-full bg-slate-900/50 border border-slate-800 focus:border-sky-500/50 rounded-xl p-3 text-xs text-slate-200 placeholder-slate-500 outline-none transition-all resize-y"
            placeholder="What is this task about?"
          />
        </div>

        {/* Comments Feed */}
        <div className="space-y-3 pt-4 border-t border-[#2d3748]/60">
          <label className="text-xs font-semibold text-slate-300 block">Activity & Comments</label>

          {comments.map((c) => (
            <div key={c.id || Math.random()} className="flex gap-2.5 text-xs bg-slate-900/30 p-3 rounded-xl border border-slate-800">
              <span className="w-6 h-6 rounded-full bg-purple-600 text-white flex items-center justify-center text-[10px] font-bold shrink-0">
                KA
              </span>
              <div className="space-y-1 flex-1 overflow-hidden">
                <div className="flex items-center gap-2">
                  <span className="font-semibold text-slate-200">{c.user || 'You'}</span>
                  <span className="text-[10px] text-slate-500">{c.time || 'Just now'}</span>
                </div>
                {renderCommentContent(c.text)}
              </div>
            </div>
          ))}

          {/* Screenshot Preview thumbnail before sending */}
          {screenshotPreview && (
            <div className="relative inline-block border border-sky-500 rounded-lg p-1 bg-slate-900">
              <img src={screenshotPreview} alt="Preview" className="h-20 rounded" />
              <button
                type="button"
                onClick={() => setScreenshotPreview(null)}
                className="absolute -top-2 -right-2 bg-rose-600 text-white w-5 h-5 rounded-full text-[10px] flex items-center justify-center font-bold shadow-md"
              >
                ✕
              </button>
            </div>
          )}

          <form onSubmit={handleAddComment} className="flex gap-2 pt-2">
            <span className="w-7 h-7 rounded-full bg-purple-600 text-white flex items-center justify-center text-xs font-bold shrink-0">
              KA
            </span>
            <div className="flex-1 space-y-2">
              <textarea
                value={commentText}
                onChange={(e) => setCommentText(e.target.value)}
                onPaste={handlePasteScreenshot}
                placeholder="Write a comment or paste a screenshot (Ctrl+V)..."
                rows={2}
                className="w-full bg-slate-900/80 border border-slate-700/80 rounded-xl p-3 text-xs text-slate-100 placeholder-slate-500 outline-none focus:border-sky-500 transition-all resize-none"
              />
              <div className="flex items-center justify-between">
                <label className="cursor-pointer text-slate-400 hover:text-sky-400 text-xs flex items-center gap-1 transition-colors">
                  <span>📷 Attach Image</span>
                  <input type="file" accept="image/*" onChange={handleFileSelect} className="hidden" />
                </label>

                <button
                  type="submit"
                  disabled={(!commentText.trim() && !screenshotPreview) || isAddingComment}
                  className="px-3 py-1.5 bg-sky-600 hover:bg-sky-500 disabled:opacity-50 text-white text-xs font-medium rounded-lg transition-all"
                >
                  Comment
                </button>
              </div>
            </div>
          </form>
        </div>

      </div>
    </div>
  );
}