"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Plus, LayoutGrid, List, Search, Filter } from "lucide-react";
import { tasksApi } from "@/lib/api";
import { Task, TaskStatus, STATUS_LABELS, PRIORITY_LABELS } from "@/types";
import { PageHeader, Modal, PriorityBadge, StatusBadge, EmptyState, Spinner, ConfirmDialog } from "@/components/ui";
import { formatDate, dueDateColor } from "@/lib/utils";
import { useForm } from "react-hook-form";
import toast from "react-hot-toast";

// ─── KANBAN SÜTUNLARI ─────────────────────────────────────────────────────────

const COLUMNS: { id: TaskStatus; label: string; color: string }[] = [
  { id: "bekliyor",     label: "Bekliyor",      color: "border-surface-500" },
  { id: "devam_ediyor", label: "Devam Ediyor",   color: "border-blue-500/50" },
  { id: "tamamlandi",  label: "Tamamlandı",      color: "border-green-500/50" },
  { id: "iptal",       label: "İptal",           color: "border-red-500/50" },
];

// ─── GÖREV FORMU ──────────────────────────────────────────────────────────────

function TaskForm({ task, onClose }: { task?: Task; onClose: () => void }) {
  const qc = useQueryClient();
  const { register, handleSubmit, formState: { errors } } = useForm({
    defaultValues: task ? {
      title: task.title,
      description: task.description || "",
      priority: task.priority,
      status: task.status,
      due_date: task.due_date || "",
      category: task.category || "",
    } : {
      priority: "orta",
      status: "bekliyor",
    },
  });

  const mutation = useMutation({
    mutationFn: (data: Record<string, unknown>) =>
      task ? tasksApi.update(task.id, data) : tasksApi.create(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["tasks"] });
      qc.invalidateQueries({ queryKey: ["dashboard-stats"] });
      toast.success(task ? "Görev güncellendi." : "Görev oluşturuldu.");
      onClose();
    },
    onError: () => toast.error("Bir hata oluştu."),
  });

  return (
    <form onSubmit={handleSubmit((d) => mutation.mutate(d))} className="space-y-4">
      <div>
        <label className="form-label">Başlık *</label>
        <input {...register("title", { required: "Başlık zorunlu." })} className="kaplan-input" placeholder="Görev başlığı" />
        {errors.title && <p className="text-xs text-red-400 mt-1">{errors.title.message as string}</p>}
      </div>
      <div>
        <label className="form-label">Açıklama</label>
        <textarea {...register("description")} rows={3} className="kaplan-textarea" placeholder="Görev açıklaması..." />
      </div>
      <div className="grid grid-cols-2 gap-3">
        <div>
          <label className="form-label">Öncelik</label>
          <select {...register("priority")} className="kaplan-select">
            {Object.entries(PRIORITY_LABELS).map(([k, v]) => (
              <option key={k} value={k}>{v}</option>
            ))}
          </select>
        </div>
        <div>
          <label className="form-label">Durum</label>
          <select {...register("status")} className="kaplan-select">
            {Object.entries(STATUS_LABELS).map(([k, v]) => (
              <option key={k} value={k}>{v}</option>
            ))}
          </select>
        </div>
      </div>
      <div className="grid grid-cols-2 gap-3">
        <div>
          <label className="form-label">Son Tarih</label>
          <input {...register("due_date")} type="date" className="kaplan-input" />
        </div>
        <div>
          <label className="form-label">Kategori</label>
          <input {...register("category")} className="kaplan-input" placeholder="ör: Pazarlama" />
        </div>
      </div>
      <div className="flex gap-3 justify-end pt-2">
        <button type="button" onClick={onClose} className="btn-secondary">İptal</button>
        <button type="submit" disabled={mutation.isPending} className="btn-primary">
          {mutation.isPending && <Spinner size={14} />}
          {task ? "Güncelle" : "Oluştur"}
        </button>
      </div>
    </form>
  );
}

// ─── GÖREV KARTI ─────────────────────────────────────────────────────────────

function TaskCard({ task, onEdit, onDelete }: { task: Task; onEdit: () => void; onDelete: () => void }) {
  const qc = useQueryClient();
  const statusMutation = useMutation({
    mutationFn: (status: string) => tasksApi.updateStatus(task.id, status),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["tasks"] }),
  });

  return (
    <div className="bg-surface-800 border border-surface-500 rounded-lg p-3 space-y-2.5 hover:border-surface-400 transition-colors group">
      <div className="flex items-start justify-between gap-2">
        <p className="text-sm font-medium text-surface-200 leading-snug line-clamp-2">{task.title}</p>
        <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0">
          <button onClick={onEdit} className="p-1 rounded text-surface-500 hover:text-surface-300 hover:bg-surface-600 text-xs">✏️</button>
          <button onClick={onDelete} className="p-1 rounded text-surface-500 hover:text-red-400 hover:bg-red-500/10 text-xs">🗑️</button>
        </div>
      </div>
      {task.description && (
        <p className="text-xs text-surface-500 line-clamp-2">{task.description}</p>
      )}
      <div className="flex items-center gap-2 flex-wrap">
        <PriorityBadge priority={task.priority} />
        {task.due_date && (
          <span className={`text-xs ${dueDateColor(task.due_date)}`}>
            📅 {formatDate(task.due_date)}
          </span>
        )}
        {task.category && (
          <span className="text-xs text-surface-500">{task.category}</span>
        )}
      </div>
      <select
        value={task.status}
        onChange={(e) => statusMutation.mutate(e.target.value)}
        className="w-full text-xs bg-surface-700 border border-surface-500 rounded-md px-2 py-1 text-surface-400 focus:outline-none focus:ring-1 focus:ring-brand-500"
      >
        {Object.entries(STATUS_LABELS).map(([k, v]) => (
          <option key={k} value={k}>{v}</option>
        ))}
      </select>
    </div>
  );
}

// ─── ANA SAYFA ────────────────────────────────────────────────────────────────

export default function GorevlerPage() {
  const qc = useQueryClient();
  const [view, setView] = useState<"kanban" | "liste">("kanban");
  const [search, setSearch] = useState("");
  const [filter, setFilter] = useState({ priority: "", status: "" });
  const [modal, setModal] = useState<{ open: boolean; task?: Task }>({ open: false });
  const [deleteModal, setDeleteModal] = useState<{ open: boolean; taskId?: number }>({ open: false });

  const { data: tasks = [], isLoading } = useQuery<Task[]>({
    queryKey: ["tasks", filter],
    queryFn: () => tasksApi.list(filter),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: number) => tasksApi.delete(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["tasks"] });
      toast.success("Görev silindi.");
      setDeleteModal({ open: false });
    },
  });

  const filtered = tasks.filter((t) =>
    search === "" || t.title.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="space-y-5 animate-fade-in">
      <PageHeader
        title="Görev Yönetimi"
        subtitle={`${tasks.length} görev`}
        action={
          <button onClick={() => setModal({ open: true })} className="btn-primary">
            <Plus size={16} /> Yeni Görev
          </button>
        }
      />

      {/* Araç Çubuğu */}
      <div className="flex items-center gap-3 flex-wrap">
        <div className="relative flex-1 min-w-48">
          <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-surface-500" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Görev ara..."
            className="kaplan-input pl-8 h-8 text-xs w-full"
          />
        </div>
        <select value={filter.priority} onChange={(e) => setFilter({ ...filter, priority: e.target.value })}
          className="kaplan-select h-8 text-xs w-36">
          <option value="">Tüm Öncelikler</option>
          {Object.entries(PRIORITY_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
        </select>
        <div className="flex border border-surface-500 rounded-lg overflow-hidden">
          <button onClick={() => setView("kanban")}
            className={`px-3 py-1.5 text-xs transition-colors ${view === "kanban" ? "bg-brand-600 text-white" : "text-surface-400 hover:text-surface-200"}`}>
            <LayoutGrid size={14} />
          </button>
          <button onClick={() => setView("liste")}
            className={`px-3 py-1.5 text-xs transition-colors ${view === "liste" ? "bg-brand-600 text-white" : "text-surface-400 hover:text-surface-200"}`}>
            <List size={14} />
          </button>
        </div>
      </div>

      {/* Kanban Görünümü */}
      {view === "kanban" && (
        <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
          {COLUMNS.map((col) => {
            const colTasks = filtered.filter((t) => t.status === col.id);
            return (
              <div key={col.id} className={`flex flex-col gap-3 min-h-48`}>
                <div className={`flex items-center justify-between px-3 py-2 bg-surface-700 rounded-lg border-l-2 ${col.color}`}>
                  <span className="text-sm font-medium text-surface-300">{col.label}</span>
                  <span className="text-xs bg-surface-600 text-surface-400 px-2 py-0.5 rounded-full">
                    {colTasks.length}
                  </span>
                </div>
                <div className="flex flex-col gap-2 flex-1">
                  {isLoading ? (
                    <div className="flex justify-center py-8"><Spinner /></div>
                  ) : colTasks.length > 0 ? (
                    colTasks.map((task) => (
                      <TaskCard
                        key={task.id}
                        task={task}
                        onEdit={() => setModal({ open: true, task })}
                        onDelete={() => setDeleteModal({ open: true, taskId: task.id })}
                      />
                    ))
                  ) : (
                    <div className="text-center py-8 text-xs text-surface-600">Görev yok</div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Liste Görünümü */}
      {view === "liste" && (
        <div className="kaplan-card overflow-hidden p-0">
          <table className="kaplan-table">
            <thead>
              <tr>
                <th>Görev</th>
                <th>Öncelik</th>
                <th>Durum</th>
                <th>Son Tarih</th>
                <th>Kategori</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {filtered.length === 0 ? (
                <tr><td colSpan={6} className="text-center py-12 text-surface-500">Görev bulunamadı.</td></tr>
              ) : (
                filtered.map((task) => (
                  <tr key={task.id}>
                    <td className="font-medium max-w-xs truncate">{task.title}</td>
                    <td><PriorityBadge priority={task.priority} /></td>
                    <td><StatusBadge status={task.status} /></td>
                    <td className={`text-sm ${dueDateColor(task.due_date)}`}>
                      {task.due_date ? formatDate(task.due_date) : "—"}
                    </td>
                    <td className="text-surface-500 text-sm">{task.category || "—"}</td>
                    <td>
                      <div className="flex gap-1">
                        <button onClick={() => setModal({ open: true, task })} className="btn-ghost text-xs px-2 py-1">Düzenle</button>
                        <button onClick={() => setDeleteModal({ open: true, taskId: task.id })} className="btn-ghost text-xs px-2 py-1 text-red-400">Sil</button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      )}

      {/* Modal */}
      <Modal open={modal.open} onClose={() => setModal({ open: false })} title={modal.task ? "Görevi Düzenle" : "Yeni Görev"}>
        <TaskForm task={modal.task} onClose={() => setModal({ open: false })} />
      </Modal>

      <ConfirmDialog
        open={deleteModal.open}
        onClose={() => setDeleteModal({ open: false })}
        onConfirm={() => deleteModal.taskId && deleteMutation.mutate(deleteModal.taskId)}
        title="Görevi Sil"
        description="Bu görevi silmek istediğinizden emin misiniz?"
        loading={deleteMutation.isPending}
      />
    </div>
  );
}
