"use client";

import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { api } from "@/lib/api";
import { Building2, Plus, Search, Users, Cpu, Calendar, CheckCircle, XCircle, X } from "lucide-react";

interface Tenant {
  id: string;
  name: string;
  name_ar?: string;
  email: string;
  phone?: string;
  subscription_plan: string;
  max_devices: number;
  max_users: number;
  is_active: boolean;
  devices_count?: number;
  users_count?: number;
  created_at: string;
}

export default function TenantsPage() {
  const t = useTranslations("tenants");
  const [tenants, setTenants] = useState<Tenant[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [showAddModal, setShowAddModal] = useState(false);
  const [saving, setSaving] = useState(false);
  const [newTenant, setNewTenant] = useState({
    name: "",
    name_ar: "",
    email: "",
    phone: "",
    subscription_plan: "basic",
    max_devices: 50,
    max_users: 5,
  });

  useEffect(() => {
    const fetchTenants = async () => {
      try {
        const data = await api.getTenants();
        setTenants(data.items || []);
      } catch (error) {
        console.error("Failed to fetch tenants:", error);
      } finally {
        setLoading(false);
      }
    };
    fetchTenants();
  }, []);

  const filteredTenants = tenants.filter(
    (tenant) =>
      tenant.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      tenant.email.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const handleAddTenant = async () => {
    if (!newTenant.name || !newTenant.email) return;
    
    setSaving(true);
    try {
      const created = await api.createTenant(newTenant);
      setTenants([...tenants, created]);
      setShowAddModal(false);
      setNewTenant({
        name: "",
        name_ar: "",
        email: "",
        phone: "",
        subscription_plan: "basic",
        max_devices: 50,
        max_users: 5,
      });
    } catch (error) {
      console.error("Failed to create tenant:", error);
      alert("فشل في إضافة العميل");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
            {t("title")}
          </h1>
          <p className="text-gray-500 dark:text-gray-400">{t("subtitle")}</p>
        </div>
        <button 
          onClick={() => setShowAddModal(true)}
          className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors"
        >
          <Plus className="w-5 h-5" />
          {t("addTenant")}
        </button>
      </div>

      {/* Add Tenant Modal */}
      {showAddModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          <div className="absolute inset-0 bg-black/50" onClick={() => setShowAddModal(false)} />
          <div className="relative bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-md mx-4 p-6 max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white">{t("addTenant")}</h2>
              <button onClick={() => setShowAddModal(false)} className="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded">
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1">اسم العميل (إنجليزي) *</label>
                <input
                  type="text"
                  value={newTenant.name}
                  onChange={(e) => setNewTenant({ ...newTenant, name: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-900"
                  placeholder="Company Name"
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">اسم العميل (عربي)</label>
                <input
                  type="text"
                  value={newTenant.name_ar}
                  onChange={(e) => setNewTenant({ ...newTenant, name_ar: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-900"
                  placeholder="اسم الشركة"
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">البريد الإلكتروني *</label>
                <input
                  type="email"
                  value={newTenant.email}
                  onChange={(e) => setNewTenant({ ...newTenant, email: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-900"
                  placeholder="email@company.com"
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">رقم الهاتف</label>
                <input
                  type="tel"
                  value={newTenant.phone}
                  onChange={(e) => setNewTenant({ ...newTenant, phone: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-900"
                  placeholder="+966XXXXXXXXX"
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">خطة الاشتراك</label>
                <select
                  value={newTenant.subscription_plan}
                  onChange={(e) => setNewTenant({ ...newTenant, subscription_plan: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-900"
                >
                  <option value="free">مجاني</option>
                  <option value="basic">أساسي</option>
                  <option value="professional">احترافي</option>
                  <option value="enterprise">مؤسسات</option>
                </select>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium mb-1">الحد الأقصى للأجهزة</label>
                  <input
                    type="number"
                    value={newTenant.max_devices}
                    onChange={(e) => setNewTenant({ ...newTenant, max_devices: parseInt(e.target.value) })}
                    className="w-full px-3 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-900"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1">الحد الأقصى للمستخدمين</label>
                  <input
                    type="number"
                    value={newTenant.max_users}
                    onChange={(e) => setNewTenant({ ...newTenant, max_users: parseInt(e.target.value) })}
                    className="w-full px-3 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-900"
                  />
                </div>
              </div>
            </div>
            <div className="flex gap-3 mt-6">
              <button
                onClick={() => setShowAddModal(false)}
                className="flex-1 px-4 py-2 border border-gray-200 dark:border-gray-700 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
              >
                إلغاء
              </button>
              <button
                onClick={handleAddTenant}
                disabled={saving || !newTenant.name || !newTenant.email}
                className="flex-1 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {saving ? "جاري الحفظ..." : "إضافة"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Search */}
      <div className="relative max-w-md">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
        <input
          type="text"
          placeholder={t("searchPlaceholder")}
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="w-full pl-10 pr-4 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 focus:ring-2 focus:ring-primary focus:border-transparent"
        />
      </div>

      {/* Tenants Grid */}
      {filteredTenants.length === 0 ? (
        <div className="text-center py-12 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
          <Building2 className="w-12 h-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
            {t("noTenants")}
          </h3>
          <p className="text-gray-500 dark:text-gray-400">{t("noTenantsDesc")}</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredTenants.map((tenant) => (
            <div
              key={tenant.id}
              className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5 hover:shadow-lg transition-shadow"
            >
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className="w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center">
                    <Building2 className="w-6 h-6 text-primary" />
                  </div>
                  <div>
                    <h3 className="font-semibold text-gray-900 dark:text-white">
                      {tenant.name}
                    </h3>
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                      {tenant.email}
                    </p>
                  </div>
                </div>
                <span className={`flex items-center gap-1 text-xs px-2 py-1 rounded-full ${
                  tenant.is_active
                    ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400"
                    : "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"
                }`}>
                  {tenant.is_active ? <CheckCircle className="w-3 h-3" /> : <XCircle className="w-3 h-3" />}
                  {tenant.is_active ? t("active") : t("inactive")}
                </span>
              </div>

              <div className="space-y-3">
                <div className="flex items-center justify-between text-sm">
                  <span className="text-gray-500 dark:text-gray-400 flex items-center gap-2">
                    <Cpu className="w-4 h-4" />
                    {t("devices")}
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white">
                    {tenant.devices_count || 0} / {tenant.max_devices}
                  </span>
                </div>
                <div className="flex items-center justify-between text-sm">
                  <span className="text-gray-500 dark:text-gray-400 flex items-center gap-2">
                    <Users className="w-4 h-4" />
                    {t("users")}
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white">
                    {tenant.users_count || 0} / {tenant.max_users}
                  </span>
                </div>
                <div className="flex items-center justify-between text-sm">
                  <span className="text-gray-500 dark:text-gray-400 flex items-center gap-2">
                    <Calendar className="w-4 h-4" />
                    {t("plan")}
                  </span>
                  <span className="font-medium text-primary capitalize">
                    {tenant.subscription_plan}
                  </span>
                </div>
              </div>

              <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">
                <button className="w-full py-2 text-sm text-primary hover:bg-primary/10 rounded-lg transition-colors">
                  {t("viewDetails")}
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
