import { createMemo, createSignal, For, Show } from "solid-js";
import { Clock, Link, Repeat, Trash2, Users } from "lucide-solid";

import Modal from "~/components/modal";
import { TimeTracker } from "./time-tracker";
import { RecurringConfig } from "./recurring-config";
import { useApp } from "~/lib/app-context";
import { colorOptions, getColorStyle } from "~/lib/utils";
import { apiLinkContactToTask, apiUnlinkContactFromTask } from "~/lib/api-crm";
import { notifyMentionedUsers, hasMentions } from "~/lib/mentions";
import type { Task } from "~/lib/types";
import type { Contact } from "~/lib/types-crm";

interface TaskDetailModalProps {
  task: Task | undefined;
  workspaceSlug: string;
  labels: { id: string; name: string; color: string }[];
  contacts?: Contact[];
  onClose: () => void;
  onDelete?: (taskId: string) => void;
}

export function TaskDetailModal(props: TaskDetailModalProps) {
  const app = useApp();
  const [newComment, setNewComment] = createSignal("");
  const [recurrenceRule, setRecurrenceRule] = createSignal(props.task?.recurrenceRule || "");
  const [recurrenceEnd, setRecurrenceEnd] = createSignal<string | undefined>(undefined);
  const [showContacts, setShowContacts] = createSignal(false);
  const [selectedContactId, setSelectedContactId] = createSignal("");

  const task = () => props.task;

  const updateTask = (updates: Partial<Task>) => {
    if (!task()) return;
    app.updateTask(task()!.id, current => {
      Object.assign(current, updates);
    });
  };

  const handleAddComment = async () => {
    if (!newComment().trim() || !task()) return;
    const commentContent = newComment();
    app.createTaskComment(task()!.id, commentContent);
    
    // Check for @mentions and create notifications
    if (hasMentions(commentContent) && app.state.session) {
      const workspaceSlug = task()!.workspaceSlug;
      const memberEmails = new Map(
        app.state.members.map(m => [m.name?.toLowerCase() || '', m.email])
      );
      
      await notifyMentionedUsers(
        workspaceSlug,
        app.state.session.name,
        "task",
        task()!.id,
        commentContent,
        memberEmails
      );
    }
    
    setNewComment("");
  };

  const handleLinkContact = async () => {
    if (!selectedContactId() || !task()) return;
    try {
      await apiLinkContactToTask(selectedContactId(), task()!.id);
      // Refresh contacts list would happen here
    } catch (e) {
      console.error("Failed to link contact", e);
    }
    setSelectedContactId("");
    setShowContacts(false);
  };

  return (
    <Modal 
      open={!!task()} 
      title={task()?.title ?? "Task"} 
      onClose={props.onClose}
    >
      <Show when={task()}>
        <div class="space-y-6">
          {/* Title */}
          <div>
            <label class="mb-1.5 block text-sm font-medium">Title</label>
            <input
              class="input-base w-full"
              value={task()!.title}
              onInput={e => updateTask({ title: e.currentTarget.value })}
            />
          </div>

          {/* Description */}
          <div>
            <label class="mb-1.5 block text-sm font-medium">Description</label>
            <textarea
              class="input-base min-h-24 resize-none w-full"
              value={task()!.description}
              onInput={e => updateTask({ description: e.currentTarget.value })}
            />
          </div>

          {/* Due date and Color */}
          <div class="grid gap-4 sm:grid-cols-2">
            <div>
              <label class="mb-1.5 block text-sm font-medium">Due date</label>
              <input
                class="input-base w-full"
                type="datetime-local"
                value={task()!.dueAt?.slice(0, 16) ?? ""}
                onInput={e => updateTask({ 
                  dueAt: e.currentTarget.value ? new Date(e.currentTarget.value).toISOString() : undefined 
                })}
              />
            </div>
            <div>
              <label class="mb-1.5 block text-sm font-medium">Color</label>
              <select
                class="input-base w-full"
                value={task()!.color}
                onInput={e => updateTask({ color: e.currentTarget.value })}
              >
                <For each={colorOptions}>
                  {option => <option value={option}>{option}</option>}
                </For>
              </select>
            </div>
          </div>

          {/* Recurring */}
          <div>
            <div class="flex items-center gap-2 mb-2">
              <Repeat class="w-4 h-4 text-[var(--text-muted)]" />
              <label class="text-sm font-medium">Recurring</label>
            </div>
            <RecurringConfig
              value={task()!.recurrenceRule || ""}
              onChange={(rule) => {
                updateTask({ recurrenceRule: rule });
              }}
              endDate={task()!.recurrenceEnd}
              onEndDateChange={(date) => {
                updateTask({ recurrenceEnd: date });
              }}
            />
          </div>

          {/* Labels */}
          <div>
            <label class="mb-2 block text-sm font-medium">Labels</label>
            <div class="flex flex-wrap gap-2">
              <For each={props.labels}>
                {label => {
                  const active = () => task()!.labelIds.includes(label.id);
                  return (
                    <button
                      class="rounded px-2 py-1 text-xs font-medium transition-colors"
                      classList={{ "bg-[var(--bg-muted)]": !active() }}
                      style={{
                        background: active() ? getColorStyle(label.color).bg : undefined,
                        color: active() ? getColorStyle(label.color).text : "var(--text-muted)"
                      }}
                      onClick={() => updateTask({
                        labelIds: active()
                          ? task()!.labelIds.filter(id => id !== label.id)
                          : [...task()!.labelIds, label.id]
                      })}
                    >
                      {label.name}
                    </button>
                  );
                }}
              </For>
            </div>
          </div>

          {/* Time Tracking */}
          <div>
            <div class="flex items-center gap-2 mb-2">
              <Clock class="w-4 h-4 text-[var(--text-muted)]" />
              <label class="text-sm font-medium">Time Tracking</label>
            </div>
            <TimeTracker 
              taskId={task()!.id} 
              workspaceSlug={props.workspaceSlug} 
            />
          </div>

          {/* Contacts */}
          <Show when={props.contacts && props.contacts.length > 0}>
            <div>
              <div class="flex items-center justify-between mb-2">
                <div class="flex items-center gap-2">
                  <Users class="w-4 h-4 text-[var(--text-muted)]" />
                  <label class="text-sm font-medium">Linked Contacts</label>
                </div>
                <button
                  onClick={() => setShowContacts(!showContacts())}
                  class="text-xs text-[var(--accent)] hover:underline"
                >
                  + Add contact
                </button>
              </div>
              <Show when={showContacts()}>
                <div class="flex gap-2 mb-2">
                  <select
                    class="input-base flex-1 text-sm"
                    value={selectedContactId()}
                    onChange={e => setSelectedContactId(e.currentTarget.value)}
                  >
                    <option value="">Select contact...</option>
                    <For each={props.contacts}>
                      {contact => <option value={contact.id}>{contact.firstName} {contact.lastName}</option>}
                    </For>
                  </select>
                  <button
                    onClick={handleLinkContact}
                    class="button-secondary px-3 py-1.5 text-sm"
                    disabled={!selectedContactId()}
                  >
                    Link
                  </button>
                </div>
              </Show>
            </div>
          </Show>

          {/* Attachments */}
          <div>
            <label class="mb-1.5 block text-sm font-medium">Attachments</label>
            <input
              class="input-base w-full"
              type="file"
              multiple
              onChange={e => app.attachFilesToTask(task()!.id, e.currentTarget.files)}
            />
            <Show when={task()!.attachments.length > 0}>
              <div class="mt-2 space-y-1">
                <For each={task()!.attachments}>
                  {attachment => (
                    <div class="flex items-center justify-between gap-2 rounded-md bg-[var(--bg-subtle)] px-3 py-2 text-sm">
                      <a
                        class="min-w-0 flex-1 truncate"
                        href={attachment.dataUrl}
                        download={attachment.name}
                      >
                        {attachment.name}
                      </a>
                      <span class="text-xs text-[var(--text-muted)]">
                        {Math.round(attachment.size / 1024)} KB
                      </span>
                      <button
                        class="flex h-6 w-6 items-center justify-center rounded text-[var(--text-muted)] transition-colors hover:bg-[var(--bg-muted)] hover:text-[var(--error)]"
                        onClick={() => app.removeTaskAttachment(task()!.id, attachment.id)}
                      >
                        <Trash2 size={14} />
                      </button>
                    </div>
                  )}
                </For>
              </div>
            </Show>
          </div>

          {/* Comments */}
          <div>
            <label class="mb-2 block text-sm font-medium">Comments</label>
            <div class="mb-2 space-y-2 max-h-40 overflow-y-auto">
              <For each={task()!.comments}>
                {comment => (
                  <div class="rounded-md bg-[var(--bg-subtle)] px-3 py-2">
                    <p class="text-xs font-medium">{comment.author}</p>
                    <p class="mt-1 text-sm text-[var(--text-muted)]">{comment.content}</p>
                  </div>
                )}
              </For>
            </div>
            <div class="flex gap-2">
              <input
                class="input-base flex-1"
                placeholder="Add a comment..."
                value={newComment()}
                onInput={e => setNewComment(e.currentTarget.value)}
                onKeyDown={e => e.key === "Enter" && handleAddComment()}
              />
              <button
                class="button-secondary px-3 py-2 text-sm"
                onClick={handleAddComment}
                disabled={!newComment().trim()}
              >
                Send
              </button>
            </div>
          </div>

          {/* Actions */}
          <div class="flex justify-between pt-4 border-t border-[var(--border)]">
            <Show when={props.onDelete}>
              <button
                onClick={() => {
                  props.onDelete?.(task()!.id);
                  props.onClose();
                }}
                class="px-4 py-2 rounded-lg text-red-500 hover:bg-red-50 dark:hover:bg-red-950 text-sm"
              >
                Delete Task
              </button>
            </Show>
            <div class="flex gap-2 ml-auto">
              <button
                onClick={props.onClose}
                class="px-4 py-2 rounded-lg border border-[var(--border)] hover:bg-[var(--surface-hover)] text-sm"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </Show>
    </Modal>
  );
}