import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Plus, Search, Building2, Users, X } from "lucide-react";
import { MOCK_TENANTS, type MockTenant } from "@/data/mockData";
import { StatusBadge } from "@/components/shared/StatusBadge";

export default function TenantsPage() {
  const [tenants, setTenants] = useState(MOCK_TENANTS);
  const [search, setSearch] = useState("");
  const [showCreate, setShowCreate] = useState(false);
  const [newTenant, setNewTenant] = useState({ name: "", domain: "", industry: "" });

  const filtered = tenants.filter(t =>
    t.name.toLowerCase().includes(search.toLowerCase()) ||
    t.domain.toLowerCase().includes(search.toLowerCase())
  );

  const handleCreate = () => {
    if (!newTenant.name.trim() || !newTenant.domain.trim()) return;
    const tenant: MockTenant = {
      id: tenants.length + 100,
      name: newTenant.name,
      domain: newTenant.domain,
      industry: newTenant.industry,
      status: "active",
      userCount: 0,
      createdAt: new Date().toISOString(),
    };
    setTenants(prev => [...prev, tenant]);
    setNewTenant({ name: "", domain: "", industry: "" });
    setShowCreate(false);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Tenants</h1>
          <p className="text-sm text-muted-foreground mt-1">{tenants.length} organizations registered</p>
        </div>
        <button
          onClick={() => setShowCreate(true)}
          className="flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-lg text-sm font-medium hover:bg-primary/90 transition"
        >
          <Plus className="w-4 h-4" /> New Tenant
        </button>
      </div>

      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
        <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search tenants..."
          className="w-full pl-9 pr-4 py-2 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
        {filtered.map((tenant, i) => (
          <motion.div
            key={tenant.id}
            initial={{ opacity: 0, y: 12 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: i * 0.07 }}
            className="bg-card border border-card-border rounded-xl p-5 shadow-sm hover:shadow-md transition-shadow"
            data-testid={`card-tenant-${tenant.id}`}
          >
            <div className="flex items-start justify-between mb-4">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center text-white font-bold text-sm">
                  {tenant.name.slice(0, 2).toUpperCase()}
                </div>
                <div>
                  <h3 className="font-semibold text-foreground">{tenant.name}</h3>
                  <p className="text-xs text-muted-foreground">{tenant.domain}</p>
                </div>
              </div>
              <StatusBadge status={tenant.status} />
            </div>

            <div className="flex items-center gap-4 text-xs text-muted-foreground">
              <span className="flex items-center gap-1.5">
                <Users className="w-3.5 h-3.5" />
                {tenant.userCount} users
              </span>
              {tenant.industry && (
                <span className="flex items-center gap-1.5">
                  <Building2 className="w-3.5 h-3.5" />
                  {tenant.industry}
                </span>
              )}
            </div>

            <div className="mt-3 pt-3 border-t border-border/50">
              <p className="text-xs text-muted-foreground">
                Created {new Date(tenant.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
              </p>
            </div>
          </motion.div>
        ))}
        {filtered.length === 0 && (
          <div className="col-span-full text-center py-12 text-muted-foreground text-sm">No tenants found</div>
        )}
      </div>

      <AnimatePresence>
        {showCreate && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4"
            onClick={() => setShowCreate(false)}
          >
            <motion.div initial={{ scale: 0.96, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.96, opacity: 0 }}
              onClick={e => e.stopPropagation()}
              className="bg-card rounded-2xl shadow-2xl w-full max-w-md overflow-hidden"
            >
              <div className="px-6 py-5 border-b border-border flex items-center justify-between">
                <h2 className="text-base font-semibold">Create Tenant</h2>
                <button onClick={() => setShowCreate(false)} className="p-1.5 hover:bg-muted rounded text-muted-foreground"><X className="w-4 h-4" /></button>
              </div>
              <div className="p-6 space-y-4">
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1.5 block">Company Name *</label>
                  <input value={newTenant.name} onChange={e => setNewTenant(p => ({ ...p, name: e.target.value }))}
                    placeholder="Acme Corp"
                    className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
                  />
                </div>
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1.5 block">Domain *</label>
                  <input value={newTenant.domain} onChange={e => setNewTenant(p => ({ ...p, domain: e.target.value }))}
                    placeholder="acme.corp"
                    className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
                  />
                </div>
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1.5 block">Industry</label>
                  <input value={newTenant.industry} onChange={e => setNewTenant(p => ({ ...p, industry: e.target.value }))}
                    placeholder="Technology"
                    className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
                  />
                </div>
                <div className="flex gap-3 pt-2">
                  <button onClick={() => setShowCreate(false)} className="flex-1 py-2.5 bg-muted text-muted-foreground text-sm font-medium rounded-lg">Cancel</button>
                  <button onClick={handleCreate} className="flex-1 py-2.5 bg-primary text-primary-foreground text-sm font-medium rounded-lg">Create</button>
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
