import React, { useState } from "react";
import {
  Gear,
  User,
  Bell,
  Shield,
  Buildings,
  Palette,
  Key,
  CheckCircle,
  Warning,
} from "@phosphor-icons/react";
import useAuthStore from "../store/authStore";
import toast from "react-hot-toast";
import axios from "axios";

const BRAND = "#5D4037";

const tabs = [
  { id: "profile", label: "Profile", icon: User },
  { id: "company", label: "Company", icon: Buildings },
  { id: "security", label: "Security", icon: Key },
  { id: "notifications", label: "Notifications", icon: Bell },
  { id: "appearance", label: "Appearance", icon: Palette },
];

export default function Settings() {
  const { user } = useAuthStore();
  const [activeTab, setActiveTab] = useState("profile");
  const [saving, setSaving] = useState(false);
  const [profileData, setProfileData] = useState({
    name: user?.name || "",
    email: user?.email || "",
    phone: "",
    position: "",
  });
  const [passwordData, setPasswordData] = useState({
    current_password: "",
    password: "",
    password_confirmation: "",
  });
  const [notifications, setNotifications] = useState({
    loan_requests: true,
    profit_allocation: true,
    company_updates: true,
    system_alerts: true,
    weekly_summary: false,
  });

  const saveProfile = async () => {
    setSaving(true);
    try {
      await axios.put("/api/profile", profileData);
      toast.success("Profile updated successfully");
    } catch (e) {
      toast.error(e.response?.data?.message || "Failed to update profile");
    } finally {
      setSaving(false);
    }
  };

  const changePassword = async () => {
    if (passwordData.password !== passwordData.password_confirmation) {
      toast.error("Passwords do not match");
      return;
    }
    setSaving(true);
    try {
      await axios.post("/api/change-password", passwordData);
      toast.success("Password changed successfully");
      setPasswordData({
        current_password: "",
        password: "",
        password_confirmation: "",
      });
    } catch (e) {
      toast.error(e.response?.data?.message || "Failed to change password");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="space-y-6 fade-in">
      <div>
        <h1 className="text-2xl font-extrabold text-gray-900 flex items-center gap-3">
          <Gear size={30} weight="duotone" style={{ color: BRAND }} />
          Settings
        </h1>
        <p className="text-sm text-gray-500 mt-0.5">
          Manage your account and platform preferences
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
        {/* Sidebar Tabs */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-3 h-fit">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-left transition-all text-sm font-medium mb-0.5
                ${activeTab === tab.id ? "text-white shadow-md" : "text-gray-600 hover:bg-gray-50"}`}
              style={
                activeTab === tab.id
                  ? { background: "linear-gradient(135deg,#5D4037,#6D4C41)" }
                  : {}
              }
            >
              <tab.icon size={18} weight="duotone" />
              {tab.label}
            </button>
          ))}
        </div>

        {/* Content Panel */}
        <div className="lg:col-span-3 bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          {activeTab === "profile" && (
            <div className="space-y-5">
              <h2 className="font-bold text-lg text-gray-900 border-b pb-3">
                Profile Information
              </h2>
              <div className="flex items-center gap-5 mb-4">
                <div
                  className="w-20 h-20 rounded-2xl flex items-center justify-center text-white text-3xl font-extrabold shadow-xl"
                  style={{
                    background: "linear-gradient(135deg,#5D4037,#6D4C41)",
                  }}
                >
                  {user?.name?.charAt(0).toUpperCase()}
                </div>
                <div>
                  <p className="font-bold text-gray-900 text-lg">
                    {user?.name}
                  </p>
                  <p className="text-gray-500 text-sm">{user?.email}</p>
                  <p
                    className="text-xs mt-1 px-2 py-0.5 rounded-md font-medium inline-block"
                    style={{ background: "#EFEBE9", color: "#5D4037" }}
                  >
                    {user?.company?.name || "Super Admin"}
                  </p>
                </div>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                {[
                  { label: "Full Name", key: "name", type: "text" },
                  { label: "Email Address", key: "email", type: "email" },
                  { label: "Phone Number", key: "phone", type: "tel" },
                  { label: "Job Title", key: "position", type: "text" },
                ].map((f) => (
                  <div key={f.key}>
                    <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">
                      {f.label}
                    </label>
                    <input
                      type={f.type}
                      value={profileData[f.key]}
                      onChange={(e) =>
                        setProfileData({
                          ...profileData,
                          [f.key]: e.target.value,
                        })
                      }
                      className="input-field text-sm"
                      placeholder={f.label}
                    />
                  </div>
                ))}
              </div>
              <button
                onClick={saveProfile}
                disabled={saving}
                className="px-6 py-2.5 rounded-xl text-white font-semibold transition-all hover:shadow-lg disabled:opacity-60 text-sm"
                style={{
                  background: "linear-gradient(135deg,#5D4037,#6D4C41)",
                }}
              >
                {saving ? "Saving…" : "Save Changes"}
              </button>
            </div>
          )}

          {activeTab === "security" && (
            <div className="space-y-5">
              <h2 className="font-bold text-lg text-gray-900 border-b pb-3">
                Security & Password
              </h2>
              <div className="p-4 rounded-xl border border-amber-200 bg-amber-50 flex items-start gap-3">
                <Warning
                  size={20}
                  className="text-amber-600 mt-0.5 flex-shrink-0"
                  weight="duotone"
                />
                <p className="text-sm text-amber-800">
                  Use a strong password with at least 12 characters, including
                  uppercase, lowercase, numbers, and symbols.
                </p>
              </div>
              <div className="space-y-4">
                {[
                  { label: "Current Password", key: "current_password" },
                  { label: "New Password", key: "password" },
                  {
                    label: "Confirm New Password",
                    key: "password_confirmation",
                  },
                ].map((f) => (
                  <div key={f.key}>
                    <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">
                      {f.label}
                    </label>
                    <input
                      type="password"
                      value={passwordData[f.key]}
                      onChange={(e) =>
                        setPasswordData({
                          ...passwordData,
                          [f.key]: e.target.value,
                        })
                      }
                      className="input-field text-sm"
                      placeholder="••••••••••••"
                    />
                  </div>
                ))}
              </div>
              <button
                onClick={changePassword}
                disabled={saving}
                className="px-6 py-2.5 rounded-xl text-white font-semibold text-sm transition-all hover:shadow-lg disabled:opacity-60"
                style={{
                  background: "linear-gradient(135deg,#dc2626,#b91c1c)",
                }}
              >
                {saving ? "Updating…" : "Change Password"}
              </button>
            </div>
          )}

          {activeTab === "notifications" && (
            <div className="space-y-5">
              <h2 className="font-bold text-lg text-gray-900 border-b pb-3">
                Notification Preferences
              </h2>
              <div className="space-y-4">
                {Object.entries(notifications).map(([key, value]) => (
                  <div
                    key={key}
                    className="flex items-center justify-between p-4 rounded-xl bg-gray-50 hover:bg-gray-100 transition-colors"
                  >
                    <div>
                      <p className="font-semibold text-gray-900 text-sm capitalize">
                        {key.replace(/_/g, " ")}
                      </p>
                      <p className="text-xs text-gray-500 mt-0.5">
                        Receive notifications for {key.replace(/_/g, " ")}
                      </p>
                    </div>
                    <button
                      onClick={() =>
                        setNotifications({ ...notifications, [key]: !value })
                      }
                      className={`w-12 h-6 rounded-full transition-all relative ${value ? "" : "bg-gray-300"}`}
                      style={
                        value
                          ? {
                              background:
                                "linear-gradient(90deg,#5D4037,#6D4C41)",
                            }
                          : {}
                      }
                    >
                      <div
                        className={`w-5 h-5 bg-white rounded-full absolute top-0.5 transition-all shadow-sm ${value ? "left-6" : "left-0.5"}`}
                      />
                    </button>
                  </div>
                ))}
              </div>
            </div>
          )}

          {activeTab === "appearance" && (
            <div className="space-y-5">
              <h2 className="font-bold text-lg text-gray-900 border-b pb-3">
                Appearance
              </h2>
              <div className="p-5 rounded-xl border-2 border-primary-500 bg-primary-50">
                <div className="flex items-center gap-3">
                  <div
                    className="w-8 h-8 rounded-full"
                    style={{ background: "#5D4037" }}
                  />
                  <div>
                    <p className="font-bold text-gray-900">
                      Sarkin Mota Brown Theme
                    </p>
                    <p className="text-xs text-gray-500">
                      Default brand theme — #5D4037
                    </p>
                  </div>
                  <CheckCircle
                    size={22}
                    className="ml-auto text-primary-600"
                    weight="fill"
                  />
                </div>
              </div>
            </div>
          )}

          {activeTab === "company" && (
            <div className="space-y-5">
              <h2 className="font-bold text-lg text-gray-900 border-b pb-3">
                Company Information
              </h2>
              <div className="p-4 rounded-xl" style={{ background: "#EFEBE9" }}>
                <p className="font-bold" style={{ color: "#5D4037" }}>
                  {user?.company?.name || "Super Admin Account"}
                </p>
                <p className="text-xs text-gray-600 mt-1">
                  This information is managed by your system administrator.
                </p>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 opacity-60">
                {[
                  "Company Name",
                  "Industry",
                  "Registration Number",
                  "Tax ID",
                  "Address",
                  "Website",
                ].map((l) => (
                  <div key={l}>
                    <label className="block text-xs font-bold text-gray-400 uppercase tracking-wider mb-1.5">
                      {l}
                    </label>
                    <input
                      type="text"
                      className="input-field text-sm"
                      placeholder={l}
                      disabled
                    />
                  </div>
                ))}
              </div>
              <p className="text-xs text-gray-400">
                Contact your Super Admin to update company information.
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
