import { useEffect, useMemo, useState } from "react";
import { Building2, Plus, Search } from "lucide-react";
import { motion } from "framer-motion";
import { appClient } from "@/api/appClient";
import PageHeader from "../components/shared/PageHeader";
import StatusBadge from "../components/shared/StatusBadge";
import EmptyState from "../components/shared/EmptyState";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { useToast } from "@/components/ui/use-toast";

const defaultForm = {
  name: "",
  owner_email: "",
  plan: "starter",
  status: "active",
  currency: "NGN",
  payment_provider: "paystack",
  vm_limit: 5,
  cpu_limit: 16,
  ram_limit_mb: 16384,
  disk_limit_gb: 500
};

function slugify(value) {
  return String(value || "")
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9\s-]/g, "")
    .replace(/\s+/g, "-");
}

export default function Tenants() {
  const { toast } = useToast();

  const [tenants, setTenants] = useState([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [search, setSearch] = useState("");
  const [showDialog, setShowDialog] = useState(false);
  const [editingTenant, setEditingTenant] = useState(null);
  const [form, setForm] = useState(defaultForm);

  async function loadData() {
    try {
      setLoading(true);
      const payload = await appClient.entities.Tenant.list("-created_date", 500);
      setTenants(payload || []);
    } catch (error) {
      toast({
        title: "Load failed",
        description: error?.message || "Unable to load tenants.",
        variant: "destructive"
      });
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void loadData();
  }, []);

  function openCreateDialog() {
    setEditingTenant(null);
    setForm(defaultForm);
    setShowDialog(true);
  }

  function openEditDialog(tenant) {
    setEditingTenant(tenant);
    setForm({
      name: tenant.name || "",
      owner_email: tenant.owner_email || "",
      plan: String(tenant.plan || "starter").toLowerCase(),
      status: String(tenant.status || "active").toLowerCase(),
      currency: String(tenant.currency || "NGN").toUpperCase(),
      payment_provider: String(tenant.payment_provider || "paystack").toLowerCase(),
      vm_limit: Number(tenant.vm_limit || 0),
      cpu_limit: Number(tenant.cpu_limit || 0),
      ram_limit_mb: Number(tenant.ram_limit_mb || 0),
      disk_limit_gb: Number(tenant.disk_limit_gb || 0)
    });
    setShowDialog(true);
  }

  async function handleSave() {
    if (!form.name || !form.owner_email) {
      return;
    }

    try {
      setSaving(true);
      const payload = {
        ...form,
        slug: editingTenant ? undefined : slugify(form.name),
        balance: editingTenant ? undefined : 0,
        member_emails: editingTenant ? undefined : []
      };

      if (editingTenant) {
        await appClient.entities.Tenant.update(editingTenant.id, payload);
      } else {
        await appClient.entities.Tenant.create(payload);
      }
      await loadData();
      setShowDialog(false);
      toast({
        title: editingTenant ? "Tenant updated" : "Tenant created",
        description: form.name
      });
    } catch (error) {
      toast({
        title: "Save failed",
        description: error?.message || "Unable to save tenant.",
        variant: "destructive"
      });
    } finally {
      setSaving(false);
    }
  }

  async function handleDelete(tenant) {
    try {
      await appClient.entities.Tenant.delete(tenant.id);
      await loadData();
      toast({
        title: "Tenant deleted",
        description: tenant.name,
        variant: "destructive"
      });
    } catch (error) {
      toast({
        title: "Delete failed",
        description: error?.message || "Unable to delete tenant.",
        variant: "destructive"
      });
    }
  }

  const filteredTenants = useMemo(() => {
    const needle = search.trim().toLowerCase();
    if (!needle) return tenants;
    return tenants.filter((tenant) => {
      return (
        String(tenant.name || "").toLowerCase().includes(needle) ||
        String(tenant.owner_email || "").toLowerCase().includes(needle) ||
        String(tenant.plan || "").toLowerCase().includes(needle)
      );
    });
  }, [search, tenants]);

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

  return (
    <div className="space-y-6">
      <PageHeader title="Tenants" description={`${tenants.length} organizations`}>
        <Button onClick={openCreateDialog} className="gap-2">
          <Plus className="h-4 w-4" /> New Tenant
        </Button>
      </PageHeader>

      <div className="relative max-w-sm">
        <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
        <Input
          placeholder="Search tenants..."
          value={search}
          onChange={(event) => setSearch(event.target.value)}
          className="pl-9"
        />
      </div>

      {filteredTenants.length === 0 ? (
        <EmptyState
          icon={Building2}
          title="No tenants"
          description="Create your first tenant organization."
          action={
            <Button onClick={openCreateDialog} variant="outline" className="gap-2">
              <Plus className="h-4 w-4" /> New Tenant
            </Button>
          }
        />
      ) : (
        <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
          {filteredTenants.map((tenant, index) => (
            <motion.div
              key={tenant.id}
              initial={{ opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: index * 0.04 }}
              className="surface-card group p-5 transition-all hover:border-primary/20"
            >
              <div className="mb-3 flex items-start justify-between">
                <div className="flex items-center gap-3">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-accent/30">
                    <Building2 className="h-5 w-5 text-accent" />
                  </div>
                  <div>
                    <h3 className="text-sm font-semibold text-foreground">{tenant.name}</h3>
                    <p className="text-[11px] text-muted-foreground">{tenant.owner_email}</p>
                  </div>
                </div>
                <StatusBadge status={tenant.status} />
              </div>

              <div className="grid grid-cols-2 gap-2 border-t border-border py-3 text-xs text-muted-foreground">
                <div>
                  Plan:{" "}
                  <span className="font-medium capitalize text-foreground">{tenant.plan || "-"}</span>
                </div>
                <div>
                  VMs:{" "}
                  <span className="font-medium text-foreground">{tenant.vm_limit || 0} max</span>
                </div>
                <div>
                  Balance:{" "}
                  <span className="font-medium text-foreground">
                    {tenant.currency} {(tenant.balance || 0).toLocaleString()}
                  </span>
                </div>
                <div>
                  Payment:{" "}
                  <span className="font-medium capitalize text-foreground">
                    {tenant.payment_provider || "-"}
                  </span>
                </div>
              </div>

              <div className="flex justify-end gap-2 pt-2">
                <Button
                  variant="ghost"
                  size="sm"
                  className="text-xs opacity-0 transition-opacity group-hover:opacity-100"
                  onClick={() => openEditDialog(tenant)}
                >
                  Edit
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  className="text-xs text-rose-600 opacity-0 transition-opacity hover:bg-rose-50 group-hover:opacity-100"
                  onClick={() => handleDelete(tenant)}
                >
                  Delete
                </Button>
              </div>
            </motion.div>
          ))}
        </div>
      )}

      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="max-w-xl">
          <DialogHeader>
            <DialogTitle>{editingTenant ? "Update Tenant" : "Create Tenant"}</DialogTitle>
          </DialogHeader>

          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label>Organization Name</Label>
                <Input
                  value={form.name}
                  onChange={(event) => setForm((prev) => ({ ...prev, name: event.target.value }))}
                  className="mt-1"
                />
              </div>
              <div>
                <Label>Owner Email</Label>
                <Input
                  type="email"
                  value={form.owner_email}
                  onChange={(event) =>
                    setForm((prev) => ({ ...prev, owner_email: event.target.value }))
                  }
                  className="mt-1"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
              <div>
                <Label>Plan</Label>
                <Select
                  value={form.plan}
                  onValueChange={(value) => setForm((prev) => ({ ...prev, plan: value }))}
                >
                  <SelectTrigger className="mt-1">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="starter">Starter</SelectItem>
                    <SelectItem value="professional">Professional</SelectItem>
                    <SelectItem value="enterprise">Enterprise</SelectItem>
                    <SelectItem value="custom">Custom</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>Status</Label>
                <Select
                  value={form.status}
                  onValueChange={(value) => setForm((prev) => ({ ...prev, status: value }))}
                >
                  <SelectTrigger className="mt-1">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="active">Active</SelectItem>
                    <SelectItem value="trial">Trial</SelectItem>
                    <SelectItem value="suspended">Suspended</SelectItem>
                    <SelectItem value="cancelled">Cancelled</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>Currency</Label>
                <Select
                  value={form.currency}
                  onValueChange={(value) => setForm((prev) => ({ ...prev, currency: value }))}
                >
                  <SelectTrigger className="mt-1">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="NGN">NGN</SelectItem>
                    <SelectItem value="USD">USD</SelectItem>
                    <SelectItem value="GHS">GHS</SelectItem>
                    <SelectItem value="KES">KES</SelectItem>
                    <SelectItem value="ZAR">ZAR</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>Payment</Label>
                <Select
                  value={form.payment_provider}
                  onValueChange={(value) =>
                    setForm((prev) => ({ ...prev, payment_provider: value }))
                  }
                >
                  <SelectTrigger className="mt-1">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="paystack">Paystack</SelectItem>
                    <SelectItem value="flutterwave">Flutterwave</SelectItem>
                    <SelectItem value="manual">Manual</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
              <div>
                <Label>VM Limit</Label>
                <Input
                  type="number"
                  value={form.vm_limit}
                  onChange={(event) =>
                    setForm((prev) => ({ ...prev, vm_limit: Number(event.target.value || 0) }))
                  }
                  className="mt-1"
                />
              </div>
              <div>
                <Label>CPU Limit</Label>
                <Input
                  type="number"
                  value={form.cpu_limit}
                  onChange={(event) =>
                    setForm((prev) => ({ ...prev, cpu_limit: Number(event.target.value || 0) }))
                  }
                  className="mt-1"
                />
              </div>
              <div>
                <Label>RAM Limit (MB)</Label>
                <Input
                  type="number"
                  value={form.ram_limit_mb}
                  onChange={(event) =>
                    setForm((prev) => ({
                      ...prev,
                      ram_limit_mb: Number(event.target.value || 0)
                    }))
                  }
                  className="mt-1"
                />
              </div>
              <div>
                <Label>Disk Limit (GB)</Label>
                <Input
                  type="number"
                  value={form.disk_limit_gb}
                  onChange={(event) =>
                    setForm((prev) => ({
                      ...prev,
                      disk_limit_gb: Number(event.target.value || 0)
                    }))
                  }
                  className="mt-1"
                />
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDialog(false)}>
              Cancel
            </Button>
            <Button onClick={handleSave} disabled={saving || !form.name || !form.owner_email}>
              {saving ? "Saving..." : editingTenant ? "Update Tenant" : "Create Tenant"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
