"use client";

import { useState } from "react";
import {
  Briefcase,
  Phone,
  MapPin,
  ClipboardList,
  Mail,
  Check,
  Search,
  X,
} from "lucide-react";
import PageHeader from "@/components/modals/ui/PageHeader";
import { useRouter } from "next/navigation";
import { Hospital } from "@/app/types/medicalData";
import { addHospital } from "@/app/services/hospial";
import { Country } from "country-state-city";

const ALL_COUNTRIES = Country.getAllCountries().map((country) => ({
  code: country.isoCode,
  name: country.name,
  flag: `https://flagcdn.com/w40/${country.isoCode.toLowerCase()}.png`,
}));

const HOSPITAL_TYPES = [
  "Clinic",
  "Hospital",
  "Nursing Home",
  "Diagnostic Centre",
];

const DEFAULT_COUNTRY = {
  code: "IN",
  name: "India",
  flag: "https://flagcdn.com/w40/in.png",
};

export default function AddHospitalPage({ onDone }: { onDone?: () => void }) {
  const [showCountryModal, setShowCountryModal] = useState(false);
  const [countrySearch, setCountrySearch] = useState("");
  const [emailError, setEmailError] = useState("");

  const [formData, setFormData] = useState({
    name: "",
    type: "Clinic",
    licenseNo: "",
    phone: "",
    email: "",
    country: DEFAULT_COUNTRY,
    state: "",
    city: "",
    pincode: "",
    address: "",
  });

  const filteredCountries = ALL_COUNTRIES.filter((c) =>
    c.name.toLowerCase().includes(countrySearch.toLowerCase()),
  );

  const handleCreate = async () => {
    try {
      const payload = { ...formData, country: formData.country.name };
      await addHospital(payload as Partial<Hospital>);
      onDone?.();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <div className="min-h-screen bg-[#f7f7f8] pb-24">
      <PageHeader
        icon={<Briefcase size={20} />}
        title="Hospital Setup"
        subtitle="Register your hospital or clinic to get started"
        
      />

      <main className="max-w-[760px] mx-auto p-5 sm:p-7 flex flex-col gap-4">
        <div className="flex flex-col gap-4 animate-in fade-in duration-300">
          {/* Form Section 1: Details */}
          <div className="bg-white rounded-[24px] border border-[#e5e7eb] shadow-sm p-5">
            <SectionHeading
              icon={<Briefcase size={18} />}
              iconColorClass="text-[#6366f1]"
              iconBgClass="bg-[#eef2ff]"
              title="Hospital Details"
            />

            <div className="flex flex-col gap-4">
              <CustomInput
                icon={<Briefcase size={18} />}
                label="Hospital / Clinic name *"
                value={formData.name}
                onChange={(e) =>
                  setFormData({ ...formData, name: e.target.value })
                }
                iconColor="text-[#6366f1]"
              />

              <div>
                <p className="text-sm font-medium text-[#4b5563] mb-2">
                  Type
                </p>
                <div className="flex flex-wrap gap-2">
                  {HOSPITAL_TYPES.map((t) => {
                    const isActive = formData.type === t;
                    return (
                      <button
                        key={t}
                        type="button"
                        onClick={() => setFormData({ ...formData, type: t })}
                        className={`flex items-center gap-2 px-4 py-2.5 rounded-xl border text-sm font-medium transition-all cursor-pointer ${isActive
                          ? "bg-[#f3e8ff] border-[#e9d5ff] text-[#7e22ce]"
                          : "bg-[#f9fafb] border-[#e5e7eb] text-[#4b5563] hover:bg-[#f3f4f6]"
                          }`}
                      >
                        {isActive && <Check size={16} />}
                        {t}
                      </button>
                    );
                  })}
                </div>
              </div>

              <CustomInput
                icon={<ClipboardList size={18} />}
                label="License / Registration no. (optional)"
                value={formData.licenseNo}
                onChange={(e) =>
                  setFormData({ ...formData, licenseNo: e.target.value })
                }
                iconColor="text-[#6366f1]"
              />
            </div>
          </div>

          {/* Form Section 2: Contact */}
          <div className="bg-white rounded-[24px] border border-[#e5e7eb] shadow-sm p-5">
            <SectionHeading
              icon={<Phone size={18} />}
              iconColorClass="text-[#16a34a]"
              iconBgClass="bg-[#e8f8ee]"
              title="Contact"
            />
            <div className="flex flex-col gap-4">
              <CustomInput
                icon={<Phone size={18} />}
                label="Hospital phone (optional)"
                value={formData.phone}
                onChange={(e) =>
                  setFormData({
                    ...formData,
                    phone: e.target.value.replace(/\D/g, "").slice(0, 10),
                  })
                }
                iconColor="text-[#16a34a]"
              />
              <CustomInput
                icon={<Mail size={18} />}
                label="Hospital email (optional)"
                value={formData.email}
                onChange={(e) => {
                  const value = e.target.value;

                  setFormData({
                    ...formData,
                    email: value,
                  });

                  if (
                    value &&
                    !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
                  ) {
                    setEmailError("Please enter a valid email address.");
                  } else {
                    setEmailError("");
                  }
                }}
                iconColor="text-[#16a34a]"
              />

              {emailError && (
                <p className="text-red-500 text-sm mt-1">{emailError}</p>
              )}
            </div>
          </div>

          {/* Form Section 3: Location */}
          <div className="bg-white rounded-[24px] border border-[#e5e7eb] shadow-sm p-5">
            <SectionHeading
              icon={<MapPin size={18} />}
              iconColorClass="text-[#eab308]"
              iconBgClass="bg-[#fef9c3]"
              title="Location"
            />

            <div className="flex flex-col gap-4">

              {/* Street Address First */}
              <CustomInput
                icon={<MapPin size={18} />}
                label="Street address *"
                value={formData.address}
                onChange={(e) =>
                  setFormData({ ...formData, address: e.target.value })
                }
                iconColor="text-[#eab308]"
              />

              {/* Country */}
              <button
                type="button"
                onClick={() => setShowCountryModal(true)}
                className="w-full relative flex items-center gap-3 rounded-xl border border-[#e5e7eb] bg-white px-4 py-3.5 transition-colors text-left cursor-pointer hover:bg-[#f7f7f8]"
              >
                <span className="text-[#eab308] flex-shrink-0">
                  <MapPin size={18} />
                </span>
                <div className="flex-1">
                  <p className="text-sm font-medium text-[#4b5563] mb-0.5">
                    Country
                  </p>
                  <p className="text-base text-[#111111] flex items-center gap-2">
                    <img
                      src={formData.country.flag}
                      alt={formData.country.name}
                      className="w-6 h-4 object-cover rounded shadow-sm bg-gray-200"
                    />
                    {formData.country.name} ({formData.country.code})
                    <span className="ml-1 text-xs text-[#9ca3af]">▼</span>
                  </p>
                </div>
              </button>


              {/* State */}
              <CustomInput
                icon={<MapPin size={18} />}
                label="State"
                value={formData.state}
                onChange={(e) =>
                  setFormData({ ...formData, state: e.target.value })
                }
                iconColor="text-[#eab308]"
              />

              {/* City & Pincode */}
              <div className="flex gap-4">
                <div className="flex-1">
                  <CustomInput
                    icon={<MapPin size={18} />}
                    label="City"
                    value={formData.city}
                    onChange={(e) =>
                      setFormData({ ...formData, city: e.target.value })
                    }
                    iconColor="text-[#eab308]"
                  />
                </div>

                <div className="flex-1">
                  <CustomInput
                    icon={<MapPin size={18} className="rotate-180" />}
                    label="Pincode"
                    value={formData.pincode}
                    onChange={(e) =>
                      setFormData({ ...formData, pincode: e.target.value })
                    }
                    iconColor="text-[#eab308]"
                  />
                </div>
              </div>

            </div>
          </div>

          {/* Bottom Fixed Action Bar */}
          <div className="fixed bottom-0 left-0 right-0 p-5 bg-white border-t border-[#e5e7eb] z-10 flex justify-center">
            <div className="w-full max-w-[760px] flex gap-3">
              <button
                type="button"
                onClick={() => onDone?.()}
                className="flex-1 bg-[#f3f4f6] hover:bg-[#e5e7eb] text-[#4b5563] py-4 rounded-[20px] font-medium text-base transition-colors cursor-pointer border-none"
              >
                Cancel
              </button>
              <button
                type="button"
                onClick={handleCreate}
                className="flex-[2] bg-[#4f46e5] hover:bg-[#4338ca] text-white py-4 rounded-[20px] font-medium text-base transition-colors shadow-md border-none cursor-pointer"
              >
                Create Hospital
              </button>
            </div>
          </div>
        </div>
      </main>

      {/* Country Picker Modal */}
      {showCountryModal && (
        <div className="fixed inset-0 z-[200] flex items-end justify-center sm:items-center bg-black/40 transition-opacity">
          <div className="relative bg-white w-full h-[85vh] sm:h-auto sm:max-h-[80vh] sm:max-w-[480px] flex flex-col rounded-t-[32px] sm:rounded-3xl overflow-hidden animate-in slide-in-from-bottom-10 sm:slide-in-from-bottom-0 sm:fade-in duration-200 shadow-xl">
            <div className="p-5 border-b border-[#f3f4f6] shrink-0">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-medium text-[#111111]">
                  Select a country
                </h3>
                <button
                  type="button"
                  onClick={() => setShowCountryModal(false)}
                  className="p-2 bg-[#f3f4f6] hover:bg-[#e5e7eb] rounded-full text-gray-500 transition-colors cursor-pointer border-none"
                >
                  <X size={20} />
                </button>
              </div>

              <div className="relative">
                <Search
                  size={20}
                  className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400"
                />
                <input
                  type="text"
                  placeholder="Search..."
                  value={countrySearch}
                  onChange={(e) => setCountrySearch(e.target.value)}
                  className="w-full bg-[#f9fafb] border-none border-b-2 border-b-[#4f46e5] pl-12 pr-4 py-3 text-[#111111] placeholder-[#9ca3af] text-base outline-none rounded-t-lg"
                />
              </div>
            </div>

            <div className="flex-1 overflow-y-auto p-2 min-h-0">
              {filteredCountries.map((c) => (
                <button
                  key={c.code}
                  type="button"
                  onClick={() => {
                    setFormData({ ...formData, country: c });
                    setShowCountryModal(false);
                    setCountrySearch("");
                  }}
                  className="w-full flex items-center gap-4 px-4 py-3 hover:bg-[#f3f4f6] rounded-xl transition-colors text-left cursor-pointer border-none bg-transparent"
                >
                  <img
                    src={c.flag}
                    alt={c.name}
                    className="w-7 h-5 object-cover rounded shadow-sm bg-gray-100 shrink-0"
                  />
                  <span className="text-base text-[#111111]">
                    {c.name}{" "}
                    <span className="text-[#6b7280] ml-1">({c.code})</span>
                  </span>
                  {formData.country.code === c.code && (
                    <Check size={20} className="ml-auto text-[#4f46e5]" />
                  )}
                </button>
              ))}

              {filteredCountries.length === 0 && (
                <div className="p-8 text-center text-[#6b7280]">
                  No countries found.
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function SectionHeading({
  icon,
  iconColorClass,
  iconBgClass,
  title,
}: {
  icon: React.ReactNode;
  iconColorClass: string;
  iconBgClass: string;
  title: string;
}) {
  return (
    <div className="flex items-center gap-2.5 mb-5">
      <span
        className={`w-9 h-9 rounded-lg flex items-center justify-center flex-shrink-0 ${iconBgClass} ${iconColorClass}`}
      >
        {icon}
      </span>
      <span className="text-sm font-medium text-[#4b5563]">{title}</span>
    </div>
  );
}

function CustomInput({
  icon,
  label,
  value,
  onChange,
  iconColor = "text-[#6b7280]",
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  iconColor?: string;
}) {
  return (
    <div className="flex flex-col gap-2">
      <label className="text-sm font-medium text-[#4b5563]">{label}</label>
      <div className="flex items-center gap-3 rounded-xl border border-[#e5e7eb] bg-white px-4 py-3.5 transition-colors focus-within:border-[#4f46e5]">
        <span className={`flex-shrink-0 ${iconColor}`}>{icon}</span>
        <input
          type="text"
          value={value}
          onChange={onChange}
          placeholder="Enter details..."
          className="w-full bg-transparent border-none outline-none text-base text-[#111111] placeholder:text-[#9ca3af]"
        />
      </div>
    </div>
  );
}