import { FormEvent, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { BriefcaseBusiness, Plus } from "lucide-react";

import { api, Project, Tenant } from "../api/client";
import { DataTable } from "../components/DataTable";
import { buttonClass, Field, inputClass, selectClass } from "../components/FormControls";
import { Modal } from "../components/Modal";
import { PageHeader } from "../components/PageHeader";

export function TenantsProjects() {
  const queryClient = useQueryClient();
  const tenants = useQuery({ queryKey: ["tenants"], queryFn: () => api<Tenant[]>("/tenants") });
  const projects = useQuery({ queryKey: ["projects"], queryFn: () => api<Project[]>("/projects") });
  const [tenantForm, setTenantForm] = useState({ name: "Operations", description: "Operations tenant" });
  const [projectForm, setProjectForm] = useState({ tenant_id: "", name: "Monitoring", description: "Monitoring workloads" });
  const [tenantOpen, setTenantOpen] = useState(false);
  const [projectOpen, setProjectOpen] = useState(false);

  const createTenant = useMutation({
    mutationFn: () => api<Tenant>("/tenants", { method: "POST", body: JSON.stringify(tenantForm) }),
    onSuccess: () => {
      setTenantOpen(false);
      queryClient.invalidateQueries({ queryKey: ["tenants"] });
    },
  });
  const createProject = useMutation({
    mutationFn: () => api<Project>("/projects", { method: "POST", body: JSON.stringify({ ...projectForm, tenant_id: projectForm.tenant_id || tenants.data?.[0]?.id }) }),
    onSuccess: () => {
      setProjectOpen(false);
      queryClient.invalidateQueries({ queryKey: ["projects"] });
    },
  });

  async function submitTenant(event: FormEvent) {
    event.preventDefault();
    await createTenant.mutateAsync();
  }

  async function submitProject(event: FormEvent) {
    event.preventDefault();
    await createProject.mutateAsync();
  }

  return (
    <>
      <PageHeader title="Tenants & Projects" subtitle="Define ownership boundaries for visibility, IPAM, networks, and policies." />
      <div className="space-y-4">
        <div className="flex flex-wrap gap-2">
          <button className={buttonClass} onClick={() => setTenantOpen(true)}><Plus size={16} /> Add Tenant</button>
          <button className={buttonClass} onClick={() => setProjectOpen(true)}><Plus size={16} /> Add Project</button>
        </div>
        <Modal title="Add Tenant" open={tenantOpen} onClose={() => setTenantOpen(false)}>
          <form onSubmit={submitTenant}>
          <div className="mb-4 flex items-center gap-2 font-medium"><BriefcaseBusiness size={18} /> Add Tenant</div>
          <div className="grid gap-3">
            <Field label="Name"><input className={inputClass} value={tenantForm.name} onChange={(event) => setTenantForm({ ...tenantForm, name: event.target.value })} /></Field>
            <Field label="Description"><input className={inputClass} value={tenantForm.description} onChange={(event) => setTenantForm({ ...tenantForm, description: event.target.value })} /></Field>
            <button className={buttonClass}><Plus size={16} /> Save Tenant</button>
          </div>
          </form>
        </Modal>
        <Modal title="Add Project" open={projectOpen} onClose={() => setProjectOpen(false)}>
          <form onSubmit={submitProject}>
          <div className="mb-4 font-medium">Add Project</div>
          <div className="grid gap-3">
            <Field label="Tenant"><select className={selectClass} value={projectForm.tenant_id} onChange={(event) => setProjectForm({ ...projectForm, tenant_id: event.target.value })}><option value="">Auto select</option>{(tenants.data ?? []).map((tenant) => <option key={tenant.id} value={tenant.id}>{tenant.name}</option>)}</select></Field>
            <Field label="Name"><input className={inputClass} value={projectForm.name} onChange={(event) => setProjectForm({ ...projectForm, name: event.target.value })} /></Field>
            <Field label="Description"><input className={inputClass} value={projectForm.description} onChange={(event) => setProjectForm({ ...projectForm, description: event.target.value })} /></Field>
            <button className={buttonClass}><Plus size={16} /> Save Project</button>
          </div>
          </form>
        </Modal>
        <section className="space-y-4">
          <DataTable rows={(tenants.data ?? []) as unknown as Record<string, unknown>[]} columns={[{ key: "name", label: "Tenant" }, { key: "description", label: "Description" }]} />
          <DataTable rows={(projects.data ?? []) as unknown as Record<string, unknown>[]} columns={[{ key: "name", label: "Project" }, { key: "description", label: "Description" }]} />
        </section>
      </div>
    </>
  );
}
