"use client";
import { useState } from "react";
import { Plus, Edit3, Trash2, Sun, Moon, Sunset, Clock } from "lucide-react";
import Modal from "./ui/Modal";
import Badge from "./ui/Badge";
import { formatTime } from "@/lib/utils";

interface ShiftTemplate {
  id: number;
  name: string;
  type: string;
  startTime: string;
  endTime: string;
  durationHours: number | null;
  color: string | null;
}

interface ShiftTemplateManagerProps {
  templates: ShiftTemplate[];
  departmentId: number;
  onUpdate: () => void;
}

const SHIFT_TYPE_ICONS: Record<string, React.ElementType> = {
  day: Sun,
  evening: Sunset,
  night: Moon,
  custom: Clock,
};

const SHIFT_TYPE_COLORS: Record<string, string> = {
  day: "#3B82F6",
  evening: "#F59E0B",
  night: "#8B5CF6",
  custom: "#10B981",
};

const emptyForm = {
  name: "",
  type: "day" as "day" | "evening" | "night" | "custom",
  startTime: "07:00",
  endTime: "15:00",
  durationHours: 8,
  color: "#3B82F6",
};

export default function ShiftTemplateManager({ templates, departmentId, onUpdate }: ShiftTemplateManagerProps) {
  const [showModal, setShowModal] = useState(false);
  const [editing, setEditing] = useState<ShiftTemplate | null>(null);
  const [form, setForm] = useState({ ...emptyForm });
  const [saving, setSaving] = useState(false);

  const openAdd = () => {
    setEditing(null);
    setForm({ ...emptyForm });
    setShowModal(true);
  };

  const openEdit = (tmpl: ShiftTemplate) => {
    setEditing(tmpl);
    setForm({
      name: tmpl.name,
      type: tmpl.type as typeof emptyForm.type,
      startTime: tmpl.startTime,
      endTime: tmpl.endTime,
      durationHours: tmpl.durationHours ?? 8,
      color: tmpl.color ?? "#3B82F6",
    });
    setShowModal(true);
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      if (editing) {
        await fetch("/api/shift-templates", {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ ...form, id: editing.id }),
        });
      } else {
        await fetch("/api/shift-templates", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ ...form, departmentId }),
        });
      }
      setShowModal(false);
      onUpdate();
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm("Delete this shift template?")) return;
    await fetch(`/api/shift-templates?id=${id}`, { method: "DELETE" });
    onUpdate();
  };

  const handleTypeChange = (type: typeof emptyForm.type) => {
    const defaults: Record<string, { startTime: string; endTime: string; color: string }> = {
      day: { startTime: "07:00", endTime: "15:00", color: "#3B82F6" },
      evening: { startTime: "15:00", endTime: "23:00", color: "#F59E0B" },
      night: { startTime: "23:00", endTime: "07:00", color: "#8B5CF6" },
      custom: { startTime: "08:00", endTime: "16:00", color: "#10B981" },
    };
    setForm({ ...form, type, ...defaults[type] });
  };

  return (
    <div>
      <div className="flex justify-between items-center mb-5">
        <p className="text-sm text-slate-500">Define the shift types used across your department schedules</p>
        <button
          onClick={openAdd}
          className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-xl text-sm font-medium hover:bg-blue-700 transition-colors"
        >
          <Plus size={16} />
          Add Shift Type
        </button>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {templates.map((tmpl) => {
          const Icon = SHIFT_TYPE_ICONS[tmpl.type] ?? Clock;
          return (
            <div
              key={tmpl.id}
              className="bg-white rounded-2xl border-2 overflow-hidden hover:shadow-md transition-all group"
              style={{ borderColor: tmpl.color ?? "#3B82F6" }}
            >
              <div
                className="h-2"
                style={{ backgroundColor: tmpl.color ?? "#3B82F6" }}
              />
              <div className="p-5">
                <div className="flex items-start justify-between mb-3">
                  <div
                    className="w-10 h-10 rounded-xl flex items-center justify-center"
                    style={{ backgroundColor: `${tmpl.color ?? "#3B82F6"}22`, color: tmpl.color ?? "#3B82F6" }}
                  >
                    <Icon size={20} />
                  </div>
                  <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                    <button
                      onClick={() => openEdit(tmpl)}
                      className="p-1.5 rounded-lg bg-slate-50 text-slate-500 hover:bg-slate-100"
                    >
                      <Edit3 size={14} />
                    </button>
                    <button
                      onClick={() => handleDelete(tmpl.id)}
                      className="p-1.5 rounded-lg bg-red-50 text-red-400 hover:bg-red-100"
                    >
                      <Trash2 size={14} />
                    </button>
                  </div>
                </div>
                <h3 className="font-bold text-slate-800 text-lg mb-1">{tmpl.name}</h3>
                <div className="flex items-center gap-2 mb-2">
                  <Badge color={tmpl.color ?? "#3B82F6"}>{tmpl.type}</Badge>
                  <span className="text-sm text-slate-500">{tmpl.durationHours}h shift</span>
                </div>
                <div className="text-sm text-slate-600 font-medium">
                  {formatTime(tmpl.startTime)} → {formatTime(tmpl.endTime)}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <Modal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        title={editing ? "Edit Shift Type" : "New Shift Type"}
        size="sm"
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">Shift Name *</label>
            <input
              type="text"
              value={form.name}
              onChange={(e) => setForm({ ...form, name: e.target.value })}
              placeholder="e.g., Day Shift, Night Watch..."
              className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">Shift Type</label>
            <div className="grid grid-cols-2 gap-2">
              {(["day", "evening", "night", "custom"] as const).map((t) => {
                const Icon = SHIFT_TYPE_ICONS[t];
                return (
                  <button
                    key={t}
                    onClick={() => handleTypeChange(t)}
                    className={`flex items-center gap-2 p-2.5 rounded-xl border-2 transition-all text-sm font-medium ${
                      form.type === t ? "border-blue-500 bg-blue-50 text-blue-700" : "border-slate-200 text-slate-600 hover:border-slate-300"
                    }`}
                  >
                    <Icon size={16} />
                    {t.charAt(0).toUpperCase() + t.slice(1)}
                  </button>
                );
              })}
            </div>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Start Time</label>
              <input
                type="time"
                value={form.startTime}
                onChange={(e) => setForm({ ...form, startTime: e.target.value })}
                className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">End Time</label>
              <input
                type="time"
                value={form.endTime}
                onChange={(e) => setForm({ ...form, endTime: e.target.value })}
                className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">Duration (hours)</label>
            <input
              type="number"
              value={form.durationHours}
              onChange={(e) => setForm({ ...form, durationHours: parseInt(e.target.value) || 8 })}
              min={1}
              max={24}
              className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">Color</label>
            <div className="flex items-center gap-3">
              <input
                type="color"
                value={form.color}
                onChange={(e) => setForm({ ...form, color: e.target.value })}
                className="w-12 h-10 rounded-lg border border-slate-300 cursor-pointer"
              />
              <div className="text-sm text-slate-500">{formatTime(form.startTime)} – {formatTime(form.endTime)}</div>
            </div>
          </div>

          <div className="flex gap-3 pt-2">
            <button
              onClick={handleSave}
              disabled={saving || !form.name}
              className="flex-1 py-2.5 bg-blue-600 text-white rounded-xl font-medium hover:bg-blue-700 transition-colors disabled:opacity-50"
            >
              {saving ? "Saving..." : editing ? "Save" : "Create"}
            </button>
            <button
              onClick={() => setShowModal(false)}
              className="px-4 py-2.5 border border-slate-200 rounded-xl text-slate-600 hover:bg-slate-50 transition-colors"
            >
              Cancel
            </button>
          </div>
        </div>
      </Modal>
    </div>
  );
}
