"use client";

import * as React from "react";
import { useMutation } from "@tanstack/react-query";
import { apiSend } from "@/lib/api";
import type { TaskDTO, UserDTO } from "@/lib/types";
import { STATUS_ORDER, STATUS_LABEL, PRIORITY_LABEL, CHANNEL_LABEL } from "@/lib/labels";
import { Dialog, DialogHeader, DialogBody, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Select } from "@/components/ui/select";
import { Label } from "@/components/ui/label";

const PRIORITIES = ["LOW", "MEDIUM", "HIGH"];
const CHANNELS = ["META", "GOOGLE", "TIKTOK", "OFFLINE", "SEO", "EMAIL", "OTHER"];

export function TaskDialog({
  open,
  onClose,
  onSaved,
  task,
  staff,
  canAssign,
  defaultUserId,
}: {
  open: boolean;
  onClose: () => void;
  onSaved: () => void;
  task: TaskDTO | null;
  staff: UserDTO[];
  canAssign: boolean;
  defaultUserId?: string;
}) {
  const [form, setForm] = React.useState(() => initForm(task, defaultUserId));
  const [error, setError] = React.useState("");

  React.useEffect(() => {
    setForm(initForm(task, defaultUserId));
    setError("");
  }, [task, defaultUserId, open]);

  const mutation = useMutation({
    mutationFn: async () => {
      const payload = {
        title: form.title,
        description: form.description || null,
        status: form.status,
        priority: form.priority,
        channel: form.channel || null,
        dueDate: form.dueDate ? new Date(form.dueDate).toISOString() : null,
        ...(canAssign && form.userId ? { userId: form.userId } : {}),
      };
      if (task) return apiSend(`/api/tasks/${task.id}`, "PATCH", payload);
      // Manager assigning to someone else → override endpoint; else normal create.
      if (canAssign && form.userId && form.userId !== defaultUserId) {
        return apiSend("/api/tasks/override", "POST", payload);
      }
      return apiSend("/api/tasks", "POST", payload);
    },
    onSuccess: () => {
      onSaved();
      onClose();
    },
    onError: (e) => setError(e instanceof Error ? e.message : "Failed to save"),
  });

  function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!form.title.trim()) return setError("Title is required");
    setError("");
    mutation.mutate();
  }

  return (
    <Dialog open={open} onClose={onClose}>
      <DialogHeader title={task ? "Edit Task" : "New Task"} onClose={onClose} />
      <form onSubmit={submit}>
        <DialogBody>
          <div className="space-y-1.5">
            <Label>Title</Label>
            <Input
              value={form.title}
              onChange={(e) => setForm({ ...form, title: e.target.value })}
              placeholder="e.g. Design Meta ad banner for Quayside Mall"
              autoFocus
            />
          </div>
          <div className="space-y-1.5">
            <Label>Description</Label>
            <Textarea
              value={form.description}
              onChange={(e) => setForm({ ...form, description: e.target.value })}
              placeholder="Optional details…"
            />
          </div>
          {canAssign && (
            <div className="space-y-1.5">
              <Label>Assignee</Label>
              <Select
                value={form.userId}
                onChange={(e) => setForm({ ...form, userId: e.target.value })}
              >
                <option value="">— Select staff —</option>
                {staff.map((s) => (
                  <option key={s.id} value={s.id}>
                    {s.name}
                    {s.position ? ` (${s.position})` : ""}
                  </option>
                ))}
              </Select>
            </div>
          )}
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5">
              <Label>Status</Label>
              <Select
                value={form.status}
                onChange={(e) => setForm({ ...form, status: e.target.value })}
              >
                {STATUS_ORDER.map((s) => (
                  <option key={s} value={s}>
                    {STATUS_LABEL[s]}
                  </option>
                ))}
              </Select>
            </div>
            <div className="space-y-1.5">
              <Label>Priority</Label>
              <Select
                value={form.priority}
                onChange={(e) => setForm({ ...form, priority: e.target.value })}
              >
                {PRIORITIES.map((p) => (
                  <option key={p} value={p}>
                    {PRIORITY_LABEL[p]}
                  </option>
                ))}
              </Select>
            </div>
            <div className="space-y-1.5">
              <Label>Channel</Label>
              <Select
                value={form.channel}
                onChange={(e) => setForm({ ...form, channel: e.target.value })}
              >
                <option value="">— None —</option>
                {CHANNELS.map((c) => (
                  <option key={c} value={c}>
                    {CHANNEL_LABEL[c]}
                  </option>
                ))}
              </Select>
            </div>
            <div className="space-y-1.5">
              <Label>Due Date</Label>
              <Input
                type="date"
                value={form.dueDate}
                onChange={(e) => setForm({ ...form, dueDate: e.target.value })}
              />
            </div>
          </div>
          {error && <p className="text-sm text-destructive">{error}</p>}
        </DialogBody>
        <DialogFooter>
          <Button type="button" variant="secondary" onClick={onClose}>
            Cancel
          </Button>
          <Button type="submit" disabled={mutation.isPending}>
            {task ? "Save changes" : "Create task"}
          </Button>
        </DialogFooter>
      </form>
    </Dialog>
  );
}

function initForm(task: TaskDTO | null, defaultUserId?: string) {
  return {
    title: task?.title ?? "",
    description: task?.description ?? "",
    status: task?.status ?? "TO_DO",
    priority: task?.priority ?? "MEDIUM",
    channel: task?.channel ?? "",
    dueDate: task?.dueDate ? task.dueDate.slice(0, 10) : "",
    userId: task?.userId ?? defaultUserId ?? "",
  };
}
