import React, { useMemo, useState } from "react";
import {
  BedDouble,
  Plus,
  Search,
  Trash2,
  Edit3,
  ClipboardList,
  X,
  Layers3,
  CheckCircle2,
} from "lucide-react";

const initialRoomTypes = [
  {
    id: 1,
    roomType: "Single Occupancy",
    description: "One student per room with private space",
    status: "Active",
  },
  {
    id: 2,
    roomType: "Double Sharing",
    description: "Two students sharing one room",
    status: "Active",
  },
  {
    id: 3,
    roomType: "Triple Sharing",
    description: "Three students sharing one room",
    status: "Inactive",
  },
];

const InputField = ({ label, icon: Icon, value, onChange, placeholder }) => (
  <div>
    <label className="text-sm font-semibold text-gray-600 mb-2 block">
      {label}
    </label>

    <div className="relative">
      <Icon
        size={18}
        className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"
      />

      <input
        type="text"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        className="w-full h-12 rounded-2xl border border-gray-200 bg-white pl-11 pr-4 text-sm outline-none focus:ring-4 focus:ring-blue-100 focus:border-blue-500 transition-all"
      />
    </div>
  </div>
);

const SelectField = ({ label, icon: Icon, value, onChange, options }) => (
  <div>
    <label className="text-sm font-semibold text-gray-600 mb-2 block">
      {label}
    </label>

    <div className="relative">
      <Icon
        size={18}
        className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"
      />

      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className="w-full h-12 rounded-2xl border border-gray-200 bg-white pl-11 pr-4 text-sm outline-none focus:ring-4 focus:ring-blue-100 focus:border-blue-500 transition-all appearance-none"
      >
        {options.map((item) => (
          <option key={item}>{item}</option>
        ))}
      </select>
    </div>
  </div>
);

export default function AddRoomType() {
  const [roomTypes, setRoomTypes] = useState(initialRoomTypes);

  const [search, setSearch] = useState("");

  const [showModal, setShowModal] = useState(false);

  const [editId, setEditId] = useState(null);

  const emptyForm = {
    roomType: "",
    description: "",
    status: "Active",
  };

  const [form, setForm] = useState(emptyForm);

  const filteredRoomTypes = useMemo(() => {
    return roomTypes.filter((item) =>
      item.roomType.toLowerCase().includes(search.toLowerCase()),
    );
  }, [roomTypes, search]);

  const handleSave = () => {
    if (!form.roomType) {
      alert("Please enter room type");
      return;
    }

    if (editId) {
      setRoomTypes((prev) =>
        prev.map((item) =>
          item.id === editId ? { ...form, id: editId } : item,
        ),
      );
    } else {
      setRoomTypes((prev) => [
        ...prev,
        {
          ...form,
          id: Date.now(),
        },
      ]);
    }

    setShowModal(false);
    setForm(emptyForm);
    setEditId(null);
  };

  const handleEdit = (item) => {
    setForm(item);
    setEditId(item.id);
    setShowModal(true);
  };

  const handleDelete = (id) => {
    if (window.confirm("Delete this room type?")) {
      setRoomTypes((prev) => prev.filter((item) => item.id !== id));
    }
  };

  const stats = {
    total: roomTypes.length,
    active: roomTypes.filter((r) => r.status === "Active").length,
    inactive: roomTypes.filter((r) => r.status === "Inactive").length,
  };

  return (
    <div className="min-h-screen bg-[#f4f7fb] p-4 md:p-6 overflow-hidden">
      {/* Header */}
      <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-6">
        <div className="flex items-center gap-4">
          <div className="w-14 h-14 rounded-3xl bg-gradient-to-br from-indigo-600 to-blue-600 text-white flex items-center justify-center shadow-xl">
            <BedDouble size={28} />
          </div>

          <div>
            <h1 className="text-2xl md:text-3xl font-bold text-gray-900">
              Room Type Management
            </h1>

            <p className="text-sm text-gray-500 mt-1">
              Add and manage hostel room types
            </p>
          </div>
        </div>

        <button
          onClick={() => {
            setShowModal(true);
            setEditId(null);
            setForm(emptyForm);
          }}
          className="h-12 px-5 rounded-2xl bg-gradient-to-r from-indigo-600 to-blue-600 text-white font-semibold flex items-center justify-center gap-2 shadow-lg hover:scale-105 transition-all"
        >
          <Plus size={18} />
          Add Room Type
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        {[
          {
            title: "Total Room Types",
            value: stats.total,
            icon: ClipboardList,
            bg: "bg-blue-100",
            color: "text-blue-600",
          },
          {
            title: "Active Types",
            value: stats.active,
            icon: CheckCircle2,
            bg: "bg-green-100",
            color: "text-green-600",
          },
          {
            title: "Inactive Types",
            value: stats.inactive,
            icon: Layers3,
            bg: "bg-red-100",
            color: "text-red-600",
          },
        ].map((item) => (
          <div
            key={item.title}
            className="bg-white rounded-3xl border border-gray-100 p-5 shadow-sm hover:shadow-lg transition-all"
          >
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">{item.title}</p>

                <h2 className="text-3xl font-bold text-gray-900 mt-2">
                  {item.value}
                </h2>
              </div>

              <div
                className={`w-14 h-14 rounded-2xl ${item.bg} flex items-center justify-center`}
              >
                <item.icon className={item.color} size={26} />
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Table */}
      <div className="bg-white rounded-3xl border border-gray-100 shadow-sm overflow-hidden">
        <div className="p-5 border-b border-gray-100 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          <div>
            <h2 className="text-lg font-bold text-gray-900">Room Type List</h2>

            <p className="text-sm text-gray-400 mt-1">
              Records: 1 to {filteredRoomTypes.length} of {roomTypes.length}
            </p>
          </div>

          <div className="relative w-full md:w-80">
            <Search
              size={18}
              className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"
            />

            <input
              type="text"
              placeholder="Search room type..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full h-12 rounded-2xl border border-gray-200 bg-white pl-11 pr-4 text-sm outline-none focus:ring-4 focus:ring-blue-100 focus:border-blue-500 transition-all"
            />
          </div>
        </div>

        {/* Desktop Table */}
        <div className="hidden lg:block overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                {["Room Type", "Description", "Status", "Action"].map(
                  (head) => (
                    <th
                      key={head}
                      className="px-6 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-500"
                    >
                      {head}
                    </th>
                  ),
                )}
              </tr>
            </thead>

            <tbody>
              {filteredRoomTypes.map((item) => (
                <tr
                  key={item.id}
                  className="border-b border-gray-100 hover:bg-blue-50/40 transition-all"
                >
                  <td className="px-6 py-5">
                    <div className="flex items-center gap-3">
                      <div className="w-11 h-11 rounded-2xl bg-indigo-100 text-indigo-600 flex items-center justify-center">
                        <BedDouble size={20} />
                      </div>

                      <div>
                        <h2 className="font-bold text-gray-900">
                          {item.roomType}
                        </h2>
                      </div>
                    </div>
                  </td>

                  <td className="px-6 py-5 text-gray-600 max-w-md">
                    {item.description}
                  </td>

                  <td className="px-6 py-5">
                    <span
                      className={`px-3 py-1 rounded-full text-xs font-bold ${
                        item.status === "Active"
                          ? "bg-green-100 text-green-700"
                          : "bg-red-100 text-red-700"
                      }`}
                    >
                      {item.status}
                    </span>
                  </td>

                  <td className="px-6 py-5">
                    <div className="flex items-center gap-2">
                      <button
                        onClick={() => handleEdit(item)}
                        className="w-9 h-9 rounded-xl bg-blue-100 text-blue-600 flex items-center justify-center hover:scale-105 transition-all"
                      >
                        <Edit3 size={16} />
                      </button>

                      <button
                        onClick={() => handleDelete(item.id)}
                        className="w-9 h-9 rounded-xl bg-red-100 text-red-600 flex items-center justify-center hover:scale-105 transition-all"
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Mobile Cards */}
        <div className="lg:hidden p-4 space-y-4">
          {filteredRoomTypes.map((item) => (
            <div
              key={item.id}
              className="border border-gray-100 rounded-3xl p-5 shadow-sm"
            >
              <div className="flex items-center justify-between mb-4">
                <h2 className="font-bold text-lg text-gray-900">
                  {item.roomType}
                </h2>

                <span
                  className={`px-3 py-1 rounded-full text-xs font-bold ${
                    item.status === "Active"
                      ? "bg-green-100 text-green-700"
                      : "bg-red-100 text-red-700"
                  }`}
                >
                  {item.status}
                </span>
              </div>

              <p className="text-sm text-gray-600 leading-relaxed">
                {item.description}
              </p>

              <div className="flex gap-3 mt-5">
                <button
                  onClick={() => handleEdit(item)}
                  className="flex-1 h-11 rounded-2xl bg-blue-100 text-blue-700 font-semibold flex items-center justify-center gap-2"
                >
                  <Edit3 size={16} />
                  Edit
                </button>

                <button
                  onClick={() => handleDelete(item.id)}
                  className="flex-1 h-11 rounded-2xl bg-red-100 text-red-700 font-semibold flex items-center justify-center gap-2"
                >
                  <Trash2 size={16} />
                  Delete
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Modal */}
      {showModal && (
        <div className="fixed inset-0 z-50 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4">
          <div className="bg-white rounded-[32px] w-full max-w-2xl shadow-2xl overflow-hidden">
            <div className="flex items-center justify-between p-6 border-b border-gray-100">
              <div>
                <h2 className="text-2xl font-bold text-gray-900">
                  {editId ? "Edit Room Type" : "Add Room Type"}
                </h2>

                <p className="text-sm text-gray-400 mt-1">
                  Enter room type details
                </p>
              </div>

              <button
                onClick={() => {
                  setShowModal(false);
                  setEditId(null);
                  setForm(emptyForm);
                }}
                className="w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center transition-all"
              >
                <X size={18} />
              </button>
            </div>

            <div className="p-6 space-y-5">
              <InputField
                label="Room Type *"
                icon={BedDouble}
                value={form.roomType}
                onChange={(v) => setForm({ ...form, roomType: v })}
                placeholder="Enter room type"
              />

              <SelectField
                label="Status"
                icon={CheckCircle2}
                value={form.status}
                onChange={(v) => setForm({ ...form, status: v })}
                options={["Active", "Inactive"]}
              />

              <div>
                <label className="text-sm font-semibold text-gray-600 mb-2 block">
                  Description
                </label>

                <textarea
                  rows={5}
                  value={form.description}
                  onChange={(e) =>
                    setForm({
                      ...form,
                      description: e.target.value,
                    })
                  }
                  placeholder="Write room type description..."
                  className="w-full rounded-2xl border border-gray-200 bg-white p-4 text-sm outline-none focus:ring-4 focus:ring-blue-100 focus:border-blue-500 transition-all resize-none"
                />
              </div>
            </div>

            <div className="p-6 border-t border-gray-100 flex justify-end gap-3">
              <button
                onClick={() => {
                  setShowModal(false);
                  setEditId(null);
                  setForm(emptyForm);
                }}
                className="h-12 px-5 rounded-2xl border border-gray-200 text-gray-600 font-semibold hover:bg-gray-50 transition-all"
              >
                Cancel
              </button>

              <button
                onClick={handleSave}
                className="h-12 px-6 rounded-2xl bg-gradient-to-r from-indigo-600 to-blue-600 text-white font-semibold shadow-lg hover:scale-105 transition-all"
              >
                {editId ? "Update Room Type" : "Save Room Type"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
