import React, { useMemo, useState } from "react";
import {
  Building2,
  Plus,
  Search,
  Hotel,
  MapPin,
  Phone,
  Mail,
  User,
  Users,
  BedDouble,
  IndianRupee,
  Eye,
  Trash2,
  Pencil,
  X,
  CheckCircle2,
} from "lucide-react";

const hostelOptions = [
  "Arav Boys Hostel",
  "Riddhi Girls Hostel",
  "Pittal Hostel",
  "Green Valley Hostel",
];

const wardens = ["Rahul Sharma", "Neha Patel", "Aman Verma", "Priya Singh"];

const initialHotels = [
  {
    id: 1,
    hostelName: "Arav Boys Hostel",
    type: "Boys",
    rooms: 48,
    students: 120,
    warden: "Rahul Sharma",
    phone: "9876543210",
    email: "aravhostel@gmail.com",
    address: "Near School Campus, Bhopal",
    status: "Active",
  },
  {
    id: 2,
    hostelName: "Riddhi Girls Hostel",
    type: "Girls",
    rooms: 36,
    students: 96,
    warden: "Priya Singh",
    phone: "9876500000",
    email: "riddhihostel@gmail.com",
    address: "MP Nagar, Bhopal",
    status: "Active",
  },
  {
    id: 3,
    hostelName: "Pittal Hostel",
    type: "Mixed",
    rooms: 28,
    students: 65,
    warden: "Aman Verma",
    phone: "9898989898",
    email: "pittalhostel@gmail.com",
    address: "Kolar Road, Bhopal",
    status: "Inactive",
  },
];

const emptyForm = {
  hostelName: "",
  type: "",
  rooms: "",
  students: "",
  warden: "",
  phone: "",
  email: "",
  address: "",
  status: "Active",
};

export default function AddHostel() {
  const [hostels, setHostels] = useState(initialHotels);
  const [search, setSearch] = useState("");
  const [showModal, setShowModal] = useState(false);
  const [selected, setSelected] = useState(null);

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

  const filteredHostels = useMemo(() => {
    return hostels.filter(
      (item) =>
        item.hostelName.toLowerCase().includes(search.toLowerCase()) ||
        item.warden.toLowerCase().includes(search.toLowerCase()) ||
        item.type.toLowerCase().includes(search.toLowerCase()),
    );
  }, [search, hostels]);

  const totalStudents = hostels.reduce(
    (sum, hostel) => sum + Number(hostel.students),
    0,
  );

  const totalRooms = hostels.reduce(
    (sum, hostel) => sum + Number(hostel.rooms),
    0,
  );

  const saveHostel = () => {
    if (!form.hostelName || !form.type || !form.rooms || !form.warden) {
      return alert("Please fill all required fields");
    }

    setHostels((prev) => [
      ...prev,
      {
        ...form,
        id: Date.now(),
      },
    ]);

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

  const deleteHostel = (id) => {
    if (window.confirm("Delete this hostel?")) {
      setHostels((prev) => prev.filter((item) => item.id !== id));
    }
  };

  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-blue-600 to-indigo-600 text-white flex items-center justify-center shadow-xl">
            <Hotel size={28} />
          </div>

          <div>
            <h1 className="text-2xl md:text-3xl font-bold text-gray-900">
              Hostel Management
            </h1>
            <p className="text-sm text-gray-500 mt-1">
              Manage school hostels, wardens and student accommodation
            </p>
          </div>
        </div>

        <button
          onClick={() => setShowModal(true)}
          className="h-11 px-5 rounded-2xl bg-gradient-to-r from-blue-600 to-indigo-600 text-white font-semibold flex items-center justify-center gap-2 shadow-lg hover:scale-[1.02] transition-all"
        >
          <Plus size={18} />
          Add Hostel
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 xl:grid-cols-4 gap-4 mb-6">
        {[
          {
            title: "Total Hostels",
            value: hostels.length,
            icon: Building2,
            bg: "bg-blue-100",
            color: "text-blue-600",
          },
          {
            title: "Total Rooms",
            value: totalRooms,
            icon: BedDouble,
            bg: "bg-green-100",
            color: "text-green-600",
          },
          {
            title: "Students",
            value: totalStudents,
            icon: Users,
            bg: "bg-purple-100",
            color: "text-purple-600",
          },
          {
            title: "Active Hostels",
            value: hostels.filter((h) => h.status === "Active").length,
            icon: CheckCircle2,
            bg: "bg-orange-100",
            color: "text-orange-600",
          },
        ].map((item) => {
          const Icon = item.icon;

          return (
            <div
              key={item.title}
              className="bg-white rounded-3xl border border-gray-100 shadow-sm p-5 flex items-center justify-between hover:shadow-lg transition-all"
            >
              <div>
                <p className="text-sm text-gray-500 font-medium">
                  {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`}
              >
                <Icon className={item.color} size={26} />
              </div>
            </div>
          );
        })}
      </div>

      {/* Search */}
      <div className="bg-white rounded-3xl border border-gray-100 shadow-sm p-5 mb-6">
        <div className="relative w-full md:w-96">
          <Search size={18} className="absolute left-4 top-3.5 text-gray-400" />

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

      {/* Hostel Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
        {filteredHostels.map((item) => (
          <div
            key={item.id}
            className="bg-white rounded-3xl border border-gray-100 shadow-sm overflow-hidden hover:shadow-xl transition-all"
          >
            <div className="bg-gradient-to-r from-blue-600 to-indigo-600 p-5 text-white">
              <div className="flex items-center justify-between">
                <h2 className="text-lg font-bold">{item.hostelName}</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-600"
                  }`}
                >
                  {item.status}
                </span>
              </div>

              <p className="text-sm text-blue-100 mt-1">{item.type} Hostel</p>
            </div>

            <div className="p-5 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="bg-gray-50 rounded-2xl p-4">
                  <p className="text-xs text-gray-500 font-medium">Rooms</p>
                  <h3 className="text-2xl font-bold text-gray-900 mt-1">
                    {item.rooms}
                  </h3>
                </div>

                <div className="bg-gray-50 rounded-2xl p-4">
                  <p className="text-xs text-gray-500 font-medium">Students</p>
                  <h3 className="text-2xl font-bold text-gray-900 mt-1">
                    {item.students}
                  </h3>
                </div>
              </div>

              <div className="space-y-3">
                <div className="flex items-center gap-3">
                  <User size={16} className="text-blue-500" />
                  <span className="text-sm text-gray-700">{item.warden}</span>
                </div>

                <div className="flex items-center gap-3">
                  <Phone size={16} className="text-green-500" />
                  <span className="text-sm text-gray-700">{item.phone}</span>
                </div>

                <div className="flex items-center gap-3">
                  <Mail size={16} className="text-purple-500" />
                  <span className="text-sm text-gray-700 break-all">
                    {item.email}
                  </span>
                </div>

                <div className="flex items-start gap-3">
                  <MapPin size={16} className="text-orange-500 mt-0.5" />
                  <span className="text-sm text-gray-700">{item.address}</span>
                </div>
              </div>

              <div className="flex items-center justify-end gap-2 pt-2">
                <button
                  onClick={() => setSelected(item)}
                  className="w-10 h-10 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center hover:scale-105 transition-all"
                >
                  <Eye size={18} />
                </button>

                <button className="w-10 h-10 rounded-xl bg-yellow-50 text-yellow-600 flex items-center justify-center hover:scale-105 transition-all">
                  <Pencil size={18} />
                </button>

                <button
                  onClick={() => deleteHostel(item.id)}
                  className="w-10 h-10 rounded-xl bg-red-50 text-red-500 flex items-center justify-center hover:scale-105 transition-all"
                >
                  <Trash2 size={18} />
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Add 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-3xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-6 border-b border-gray-100">
              <div>
                <h2 className="text-2xl font-bold text-gray-900">Add Hostel</h2>
                <p className="text-sm text-gray-500 mt-1">
                  Create new hostel for school management
                </p>
              </div>

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

            <div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-5">
              {[
                {
                  label: "Hostel Name *",
                  value: form.hostelName,
                  key: "hostelName",
                },
                {
                  label: "Number of Rooms *",
                  value: form.rooms,
                  key: "rooms",
                  type: "number",
                },
                {
                  label: "Students Capacity",
                  value: form.students,
                  key: "students",
                  type: "number",
                },
                {
                  label: "Phone Number",
                  value: form.phone,
                  key: "phone",
                },
                {
                  label: "Email Address",
                  value: form.email,
                  key: "email",
                },
              ].map((field) => (
                <div key={field.key}>
                  <label className="text-sm font-semibold text-gray-700 mb-2 block">
                    {field.label}
                  </label>

                  <input
                    type={field.type || "text"}
                    value={field.value}
                    onChange={(e) =>
                      setForm({
                        ...form,
                        [field.key]: e.target.value,
                      })
                    }
                    className="w-full h-12 rounded-2xl border border-gray-200 bg-gray-50 px-4 text-sm outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 transition-all"
                  />
                </div>
              ))}

              <div>
                <label className="text-sm font-semibold text-gray-700 mb-2 block">
                  Hostel Type *
                </label>

                <select
                  value={form.type}
                  onChange={(e) =>
                    setForm({
                      ...form,
                      type: e.target.value,
                    })
                  }
                  className="w-full h-12 rounded-2xl border border-gray-200 bg-gray-50 px-4 text-sm outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 transition-all"
                >
                  <option value="">Select Type</option>
                  <option>Boys</option>
                  <option>Girls</option>
                  <option>Mixed</option>
                </select>
              </div>

              <div>
                <label className="text-sm font-semibold text-gray-700 mb-2 block">
                  Warden *
                </label>

                <select
                  value={form.warden}
                  onChange={(e) =>
                    setForm({
                      ...form,
                      warden: e.target.value,
                    })
                  }
                  className="w-full h-12 rounded-2xl border border-gray-200 bg-gray-50 px-4 text-sm outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 transition-all"
                >
                  <option value="">Select Warden</option>

                  {wardens.map((warden) => (
                    <option key={warden}>{warden}</option>
                  ))}
                </select>
              </div>

              <div className="md:col-span-2">
                <label className="text-sm font-semibold text-gray-700 mb-2 block">
                  Address
                </label>

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

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

              <button
                onClick={saveHostel}
                className="h-11 px-6 rounded-2xl bg-gradient-to-r from-blue-600 to-indigo-600 text-white font-semibold shadow-lg hover:scale-[1.02] transition-all"
              >
                Save Hostel
              </button>
            </div>
          </div>
        </div>
      )}

      {/* View Modal */}
      {selected && (
        <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-3xl shadow-2xl w-full max-w-lg overflow-hidden">
            <div className="bg-gradient-to-r from-blue-600 to-indigo-600 p-6 text-white flex items-center justify-between">
              <div>
                <h2 className="text-2xl font-bold">{selected.hostelName}</h2>
                <p className="text-sm text-blue-100 mt-1">Hostel Details</p>
              </div>

              <button
                onClick={() => setSelected(null)}
                className="w-10 h-10 rounded-xl bg-white/20 flex items-center justify-center"
              >
                <X size={18} />
              </button>
            </div>

            <div className="p-6 space-y-4">
              {[
                ["Hostel Type", selected.type],
                ["Rooms", selected.rooms],
                ["Students", selected.students],
                ["Warden", selected.warden],
                ["Phone", selected.phone],
                ["Email", selected.email],
                ["Address", selected.address],
                ["Status", selected.status],
              ].map(([label, value]) => (
                <div
                  key={label}
                  className="flex justify-between gap-4 border-b border-gray-100 pb-3"
                >
                  <span className="text-gray-500 text-sm">{label}</span>

                  <span className="font-semibold text-gray-900 text-sm text-right">
                    {value}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
