"use client";

import { cn, priorityClass, statusClass } from "@/lib/utils";
import { PRIORITY_LABELS, STATUS_LABELS, TaskPriority, TaskStatus } from "@/types";
import { X, Loader2 } from "lucide-react";
import { useEffect, useRef } from "react";

// ─── SPINNER ─────────────────────────────────────────────────────────────────

export function Spinner({ size = 20, className }: { size?: number; className?: string }) {
  return (
    <Loader2 size={size} className={cn("animate-spin text-brand-500", className)} />
  );
}

// ─── BADGE ───────────────────────────────────────────────────────────────────

export function PriorityBadge({ priority }: { priority: string }) {
  return (
    <span className={cn("badge text-xs", priorityClass(priority))}>
      {PRIORITY_LABELS[priority as TaskPriority] || priority}
    </span>
  );
}

export function StatusBadge({ status }: { status: string }) {
  const label =
    STATUS_LABELS[status as TaskStatus] ||
    ({ aktif: "Aktif", beklemede: "Beklemede", tamamlandi: "Tamamlandı", iptal: "İptal" } as Record<string, string>)[status] ||
    status;
  return (
    <span className={cn("badge text-xs", statusClass(status))}>{label}</span>
  );
}

// ─── MODAL ────────────────────────────────────────────────────────────────────

interface ModalProps {
  open: boolean;
  onClose: () => void;
  title: string;
  children: React.ReactNode;
  size?: "sm" | "md" | "lg" | "xl";
}

export function Modal({ open, onClose, title, children, size = "md" }: ModalProps) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    if (open) document.addEventListener("keydown", handler);
    return () => document.removeEventListener("keydown", handler);
  }, [open, onClose]);

  if (!open) return null;

  const widths = { sm: "max-w-sm", md: "max-w-lg", lg: "max-w-2xl", xl: "max-w-4xl" };

  return (
    <div className="modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div
        ref={ref}
        className={cn("modal-box w-full", widths[size])}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-surface-500">
          <h2 className="text-base font-semibold text-surface-100">{title}</h2>
          <button
            onClick={onClose}
            className="p-1.5 rounded-lg text-surface-500 hover:text-surface-300 hover:bg-surface-600 transition-colors"
          >
            <X size={16} />
          </button>
        </div>
        {/* Content */}
        <div className="px-6 py-5">{children}</div>
      </div>
    </div>
  );
}

// ─── STAT CARD ────────────────────────────────────────────────────────────────

interface StatCardProps {
  title: string;
  value: string | number;
  icon: React.ReactNode;
  color?: "blue" | "green" | "amber" | "red" | "purple";
  subtitle?: string;
  trend?: number; // yüzde değişim
}

const COLOR_MAP = {
  blue: { bg: "bg-blue-500/10", text: "text-blue-400", border: "border-blue-500/20" },
  green: { bg: "bg-green-500/10", text: "text-green-400", border: "border-green-500/20" },
  amber: { bg: "bg-amber-500/10", text: "text-amber-400", border: "border-amber-500/20" },
  red: { bg: "bg-red-500/10", text: "text-red-400", border: "border-red-500/20" },
  purple: { bg: "bg-purple-500/10", text: "text-purple-400", border: "border-purple-500/20" },
};

export function StatCard({ title, value, icon, color = "blue", subtitle, trend }: StatCardProps) {
  const c = COLOR_MAP[color];
  return (
    <div className="stat-card">
      <div className="flex items-start justify-between">
        <div className={cn("p-2.5 rounded-xl border", c.bg, c.border)}>
          <div className={cn("w-5 h-5", c.text)}>{icon}</div>
        </div>
        {trend !== undefined && (
          <span className={cn("text-xs font-medium", trend >= 0 ? "text-green-400" : "text-red-400")}>
            {trend >= 0 ? "+" : ""}{trend}%
          </span>
        )}
      </div>
      <div>
        <p className="text-2xl font-semibold text-surface-100 mt-2">{value}</p>
        <p className="text-sm text-surface-400 mt-0.5">{title}</p>
        {subtitle && <p className="text-xs text-surface-600 mt-0.5">{subtitle}</p>}
      </div>
    </div>
  );
}

// ─── PROGRESS BAR ────────────────────────────────────────────────────────────

export function ProgressBar({ value, max = 100, color }: { value: number; max?: number; color?: string }) {
  const pct = Math.min((value / max) * 100, 100);
  const barColor = color || (pct >= 100 ? "bg-green-500" : pct >= 70 ? "bg-brand-500" : pct >= 40 ? "bg-amber-500" : "bg-red-500");
  return (
    <div className="w-full h-1.5 bg-surface-600 rounded-full overflow-hidden">
      <div
        className={cn("h-full rounded-full transition-all duration-500", barColor)}
        style={{ width: `${pct}%` }}
      />
    </div>
  );
}

// ─── EMPTY STATE ─────────────────────────────────────────────────────────────

export function EmptyState({ icon, title, description, action }: {
  icon: string;
  title: string;
  description?: string;
  action?: React.ReactNode;
}) {
  return (
    <div className="flex flex-col items-center justify-center py-16 text-center">
      <div className="text-4xl mb-4">{icon}</div>
      <h3 className="text-base font-medium text-surface-300 mb-2">{title}</h3>
      {description && <p className="text-sm text-surface-500 max-w-sm">{description}</p>}
      {action && <div className="mt-5">{action}</div>}
    </div>
  );
}

// ─── CONFIRM DIALOG ───────────────────────────────────────────────────────────

export function ConfirmDialog({ open, onClose, onConfirm, title, description, loading }: {
  open: boolean;
  onClose: () => void;
  onConfirm: () => void;
  title: string;
  description?: string;
  loading?: boolean;
}) {
  return (
    <Modal open={open} onClose={onClose} title={title} size="sm">
      {description && <p className="text-sm text-surface-400 mb-6">{description}</p>}
      <div className="flex gap-3 justify-end">
        <button onClick={onClose} className="btn-secondary" disabled={loading}>İptal</button>
        <button onClick={onConfirm} className="btn-danger" disabled={loading}>
          {loading ? <Spinner size={14} /> : null}
          Sil
        </button>
      </div>
    </Modal>
  );
}

// ─── PAGE HEADER ─────────────────────────────────────────────────────────────

export function PageHeader({ title, subtitle, action }: {
  title: string;
  subtitle?: string;
  action?: React.ReactNode;
}) {
  return (
    <div className="flex items-start justify-between mb-6">
      <div>
        <h2 className="text-xl font-semibold text-surface-100">{title}</h2>
        {subtitle && <p className="text-sm text-surface-500 mt-0.5">{subtitle}</p>}
      </div>
      {action && <div>{action}</div>}
    </div>
  );
}
