"use client";
import { useEffect, useState, useCallback } from "react";
import {
  Plus, X, Users, Stethoscope, UserPlus, Edit2, Trash2,
  AlertTriangle, Loader2, Shield,
} from "lucide-react";

interface StaffMember {
  id: string;
  name: string;
  email: string;
  role: string;
  isActive: boolean;
  createdAt: string;
}

const ROLE_STYLES: Record<string, { bg: string; label: string }> = {
  owner: { bg: "bg-purple-100 text-purple-700", label: "Owner" },
  doctor: { bg: "bg-blue-100 text-blue-700", label: "Doctor" },
  receptionist: { bg: "bg-green-100 text-green-700", label: "Receptionist" },
};

const AVATAR_COLORS: Record<string, string> = {
  owner: "bg-purple-500",
  doctor: "bg-blue-500",
  receptionist: "bg-green-500",
};

function getInitials(name: string) {
  return name.split(" ").map(w => w[0]).join("").toUpperCase().slice(0, 2);
}

export default function StaffPage() {
  const [staff, setStaff] = useState<StaffMember[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAdd, setShowAdd] = useState(false);
  const [editId, setEditId] = useState<string | null>(null);
  const [editName, setEditName] = useState("");
  const [editRole, setEditRole] = useState("");
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);

  // Add form
  const [addName, setAddName] = useState("");
  const [addEmail, setAddEmail] = useState("");
  const [addPassword, setAddPassword] = useState("");
  const [addRole, setAddRole] = useState("receptionist");
  const [addError, setAddError] = useState("");

  const fetchStaff = useCallback(async () => {
    const res = await fetch("/api/staff");
    if (res.ok) setStaff(await res.json());
    setLoading(false);
  }, []);

  useEffect(() => { fetchStaff(); }, [fetchStaff]);

  const handleAdd = async (e: React.FormEvent) => {
    e.preventDefault();
    setAddError("");
    setSaving(true);
    const res = await fetch("/api/staff", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: addName, email: addEmail, password: addPassword, role: addRole }),
    });
    if (!res.ok) {
      const data = await res.json();
      setAddError(data.error || "Failed to add staff");
      setSaving(false);
      return;
    }
    setShowAdd(false);
    setAddName(""); setAddEmail(""); setAddPassword(""); setAddRole("receptionist");
    setSaving(false);
    fetchStaff();
  };

  const handleEdit = async (id: string) => {
    setSaving(true);
    await fetch(`/api/staff/${id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: editName, role: editRole }),
    });
    setEditId(null);
    setSaving(false);
    fetchStaff();
  };

  const handleToggleActive = async (member: StaffMember) => {
    await fetch(`/api/staff/${member.id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ isActive: !member.isActive }),
    });
    fetchStaff();
  };

  const handleDelete = async () => {
    if (!deleteId) return;
    await fetch(`/api/staff/${deleteId}`, { method: "DELETE" });
    setDeleteId(null);
    fetchStaff();
  };

  const totalStaff = staff.length;
  const doctors = staff.filter(s => s.role === "doctor").length;
  const receptionists = staff.filter(s => s.role === "receptionist").length;

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <Loader2 className="w-8 h-8 animate-spin text-primary-500" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Staff</h1>
          <p className="text-sm text-gray-500 mt-1">Manage your clinic team members</p>
        </div>
        <button onClick={() => setShowAdd(true)} className="btn-primary flex items-center gap-2">
          <Plus size={16} /> Add Staff Member
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        {[
          { label: "Total Staff", value: totalStaff, icon: Users, color: "text-gray-600" },
          { label: "Doctors", value: doctors, icon: Stethoscope, color: "text-blue-600" },
          { label: "Receptionists", value: receptionists, icon: UserPlus, color: "text-green-600" },
        ].map(stat => (
          <div key={stat.label} className="card p-4 flex items-center gap-3">
            <div className={`p-2 rounded-lg bg-gray-50 ${stat.color}`}>
              <stat.icon size={20} />
            </div>
            <div>
              <p className="text-2xl font-bold text-gray-900">{stat.value}</p>
              <p className="text-xs text-gray-500">{stat.label}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Staff Grid */}
      {staff.length === 0 ? (
        <div className="card p-12 text-center">
          <Users className="w-12 h-12 text-gray-300 mx-auto mb-3" />
          <p className="text-gray-500 font-medium">No staff members yet</p>
          <p className="text-sm text-gray-400 mt-1">Add your first team member to get started</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {staff.map(member => {
            const roleStyle = ROLE_STYLES[member.role] || ROLE_STYLES.receptionist;
            const avatarColor = AVATAR_COLORS[member.role] || AVATAR_COLORS.receptionist;
            const isEditing = editId === member.id;

            return (
              <div key={member.id} className={`card p-4 flex items-start gap-4 ${!member.isActive ? "opacity-60" : ""}`}>
                {/* Avatar */}
                <div className={`w-11 h-11 rounded-full ${avatarColor} flex items-center justify-center shrink-0`}>
                  <span className="text-white font-bold text-sm">{getInitials(member.name)}</span>
                </div>

                {/* Info */}
                <div className="flex-1 min-w-0">
                  {isEditing ? (
                    <div className="space-y-2">
                      <input
                        className="input text-sm w-full"
                        value={editName}
                        onChange={e => setEditName(e.target.value)}
                        placeholder="Name"
                      />
                      <select
                        className="input text-sm w-full"
                        value={editRole}
                        onChange={e => setEditRole(e.target.value)}
                      >
                        <option value="doctor">Doctor</option>
                        <option value="receptionist">Receptionist</option>
                      </select>
                      <div className="flex gap-2">
                        <button
                          onClick={() => handleEdit(member.id)}
                          disabled={saving}
                          className="btn-primary text-xs px-3 py-1.5"
                        >
                          Save
                        </button>
                        <button
                          onClick={() => setEditId(null)}
                          className="text-xs px-3 py-1.5 text-gray-500 hover:text-gray-700"
                        >
                          Cancel
                        </button>
                      </div>
                    </div>
                  ) : (
                    <>
                      <div className="flex items-center gap-2">
                        <p className="font-semibold text-gray-900 truncate">{member.name}</p>
                        <span className={`px-2 py-0.5 rounded-full text-[10px] font-bold uppercase ${roleStyle.bg}`}>
                          {roleStyle.label}
                        </span>
                      </div>
                      <p className="text-sm text-gray-500 truncate">{member.email}</p>
                    </>
                  )}
                </div>

                {/* Actions */}
                {!isEditing && member.role !== "owner" && (
                  <div className="flex items-center gap-1 shrink-0">
                    {/* Active toggle */}
                    <button
                      onClick={() => handleToggleActive(member)}
                      title={member.isActive ? "Deactivate" : "Activate"}
                      className={`w-10 h-5 rounded-full relative transition-colors ${
                        member.isActive ? "bg-green-500" : "bg-gray-300"
                      }`}
                    >
                      <div className={`w-4 h-4 bg-white rounded-full absolute top-0.5 transition-all shadow-sm ${
                        member.isActive ? "left-5" : "left-0.5"
                      }`} />
                    </button>
                    <button
                      onClick={() => { setEditId(member.id); setEditName(member.name); setEditRole(member.role); }}
                      className="p-1.5 text-gray-400 hover:text-primary-600 hover:bg-gray-100 rounded-lg transition-colors"
                    >
                      <Edit2 size={14} />
                    </button>
                    <button
                      onClick={() => setDeleteId(member.id)}
                      className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                    >
                      <Trash2 size={14} />
                    </button>
                  </div>
                )}
                {member.role === "owner" && (
                  <Shield size={16} className="text-purple-400 shrink-0 mt-1" />
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* Add Modal */}
      {showAdd && (
        <div className="modal-overlay" onClick={() => setShowAdd(false)}>
          <div className="card p-6 w-full max-w-md animate-scale-in" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-5">
              <h2 className="text-lg font-bold text-gray-900">Add Staff Member</h2>
              <button onClick={() => setShowAdd(false)} className="text-gray-400 hover:text-gray-600">
                <X size={20} />
              </button>
            </div>
            <form onSubmit={handleAdd} className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Name</label>
                <input className="input w-full" value={addName} onChange={e => setAddName(e.target.value)} required />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
                <input className="input w-full" type="email" value={addEmail} onChange={e => setAddEmail(e.target.value)} required />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Password</label>
                <input className="input w-full" type="password" value={addPassword} onChange={e => setAddPassword(e.target.value)} required minLength={6} />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Role</label>
                <select className="input w-full" value={addRole} onChange={e => setAddRole(e.target.value)}>
                  <option value="doctor">Doctor</option>
                  <option value="receptionist">Receptionist</option>
                </select>
              </div>
              {addError && <p className="text-sm text-red-600">{addError}</p>}
              <button type="submit" disabled={saving} className="btn-primary w-full flex items-center justify-center gap-2">
                {saving ? <Loader2 size={16} className="animate-spin" /> : <Plus size={16} />}
                Add Staff Member
              </button>
            </form>
          </div>
        </div>
      )}

      {/* Delete Confirm Modal */}
      {deleteId && (
        <div className="modal-overlay" onClick={() => setDeleteId(null)}>
          <div className="card p-6 w-full max-w-sm animate-scale-in" onClick={e => e.stopPropagation()}>
            <div className="flex items-center gap-3 mb-4">
              <div className="p-2 rounded-full bg-red-100">
                <AlertTriangle size={20} className="text-red-600" />
              </div>
              <h2 className="text-lg font-bold text-gray-900">Delete Staff Member?</h2>
            </div>
            <p className="text-sm text-gray-500 mb-5">This action cannot be undone. The staff member will be permanently removed.</p>
            <div className="flex gap-3">
              <button onClick={() => setDeleteId(null)} className="flex-1 px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors">
                Cancel
              </button>
              <button onClick={handleDelete} className="flex-1 px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors">
                Delete
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
