import { useState, ReactNode } from "react";
import { router } from "@inertiajs/react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { PoundsField, IntegerField } from "@/components/ui/number-field";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";
import { Plus, Pencil, Trash2, X, CheckCircle2, XCircle, AlertTriangle } from "lucide-react";
import AdminLayout from "@/layouts/AdminLayout";

interface Company {
  id: string;
  name: string;
  registration_number: string | null;
  vat_number: string | null;
  contact_phone: string | null;
  contact_email: string | null;
  address: string | null;
  account_admin_name: string | null;
  accounts_contact_name: string | null;
  accounts_contact_email: string | null;
  status: string;
  payment_terms_days: number;
  credit_limit_cents: number;
  credit_available_cents: number;
  company_type: string;
  notes: string | null;
  created_at: string;
}

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? "";

const emptyForm = {
  name: "",
  registration_number: "",
  vat_number: "",
  contact_phone: "",
  contact_email: "",
  address: "",
  account_admin_name: "",
  accounts_contact_name: "",
  accounts_contact_email: "",
  status: "pending",
  payment_terms_days: 30,
  credit_limit_cents: 0,
  credit_available_cents: 0,
  company_type: "customer_company",
  notes: "",
};

const CompaniesPage = () => {
  const queryClient = useQueryClient();
  const [showForm, setShowForm] = useState(false);
  const [editing, setEditing] = useState<Company | null>(null);
  const [form, setForm] = useState(emptyForm);
  const [typeFilter, setTypeFilter] = useState<string>("all");
  const [statusFilter, setStatusFilter] = useState<string>("all");

  const { data: companies, isLoading } = useQuery({
    queryKey: ["training_companies"],
    queryFn: async (): Promise<Company[]> => {
      const res = await fetch("/api/admin/training-companies");
      if (!res.ok) return [];
      return res.json();
    },
  });

  const draftCount = companies?.filter((c) => c.status === "draft").length || 0;
  const pendingCount = companies?.filter((c) => c.status === "pending").length || 0;

  const filtered = companies?.filter((c) => {
    const typeMatch = typeFilter === "all" || c.company_type === typeFilter;
    const statusMatch = statusFilter === "all" || c.status === statusFilter;
    return typeMatch && statusMatch;
  });

  const saveMutation = useMutation({
    mutationFn: async (values: typeof form) => {
      const path = editing
        ? `/api/admin/training-companies/${editing.id}`
        : `/api/admin/training-companies`;
      const method = editing ? "PUT" : "POST";
      const res = await fetch(path, {
        method,
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
        body: JSON.stringify(values),
      });
      if (!res.ok) throw new Error("Failed to save company");
      return res.json().catch(() => null);
    },
    onSuccess: (data: any) => {
      queryClient.invalidateQueries({ queryKey: ["training_companies"] });
      queryClient.invalidateQueries({ queryKey: ["companies-count"] });
      if (!editing && data?.credentials_sent && data?.contact_email) {
        toast.success(`Company added — login details emailed to ${data.contact_email}`);
      } else {
        toast.success(editing ? "Company updated" : "Company added");
      }
      resetForm();
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const res = await fetch(`/api/admin/training-companies/${id}`, {
        method: "DELETE",
        headers: { "Accept": "application/json", "X-Requested-With": "XMLHttpRequest", "X-CSRF-TOKEN": csrfToken() },
      });
      if (!res.ok) {
        const data = await res.json().catch(() => null);
        const err = new Error(data?.error || data?.message || "Failed to delete company");
        (err as any).ordersUrl = data?.orders_url;
        throw err;
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["training_companies"] });
      queryClient.invalidateQueries({ queryKey: ["companies-count"] });
      toast.success("Company deleted");
    },
    onError: (e: Error) => {
      const ordersUrl = (e as any).ordersUrl;
      toast.error(e.message, {
        duration: 10000,
        action: ordersUrl
          ? { label: "View orders", onClick: () => router.visit(ordersUrl) }
          : undefined,
      });
    },
  });

  const approveMutation = useMutation({
    mutationFn: async (id: string) => {
      const res = await fetch(`/api/admin/companies/${id}/approve`, {
        method: "POST",
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
      });
      if (!res.ok) throw new Error("Failed to approve");
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["training_companies"] });
      toast.success("Company approved — applicants notified");
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const rejectMutation = useMutation({
    mutationFn: async (id: string) => {
      const res = await fetch(`/api/admin/companies/${id}/reject`, {
        method: "POST",
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
        body: JSON.stringify({ reason: "" }),
      });
      if (!res.ok) throw new Error("Failed to reject");
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["training_companies"] });
      toast.success("Company rejected");
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const resetForm = () => {
    setForm(emptyForm);
    setEditing(null);
    setShowForm(false);
  };

  const statusColor = (s: string) => {
    switch (s) {
      case "approved": return "default";
      case "pending": return "secondary";
      case "draft": return "outline";
      case "suspended": return "destructive";
      default: return "outline";
    }
  };

  const typeLabel = (t: string) => {
    switch (t) {
      case "training_company": return "Training Company";
      case "hybrid": return "Hybrid";
      default: return "Purchasing Company";
    }
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-foreground">Companies</h1>
        <div className="flex items-center gap-3">
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="w-[160px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Statuses</SelectItem>
              <SelectItem value="draft">Draft</SelectItem>
              <SelectItem value="pending">Pending</SelectItem>
              <SelectItem value="approved">Approved</SelectItem>
              <SelectItem value="suspended">Suspended</SelectItem>
            </SelectContent>
          </Select>
          <Select value={typeFilter} onValueChange={setTypeFilter}>
            <SelectTrigger className="w-[180px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Types</SelectItem>
              <SelectItem value="customer_company">Purchasing</SelectItem>
              <SelectItem value="training_company">Training</SelectItem>
              <SelectItem value="hybrid">Hybrid</SelectItem>
            </SelectContent>
          </Select>
          <Button variant="hero" onClick={() => { setEditing(null); setForm(emptyForm); setShowForm(true); }}>
            <Plus className="mr-2 h-4 w-4" /> Add Company
          </Button>
        </div>
      </div>

      {/* Pending Approval Banner */}
      {(draftCount > 0 || pendingCount > 0) && (
        <Card className="mb-6 border-amber-500/40 bg-amber-500/10">
          <CardContent className="py-4 flex items-center gap-3">
            <AlertTriangle className="h-5 w-5 text-amber-500 shrink-0" />
            <div>
              <p className="font-medium text-foreground">
                {draftCount + pendingCount} company {draftCount + pendingCount === 1 ? "account" : "accounts"} awaiting verification
              </p>
              <p className="text-sm text-muted-foreground">
                Review and approve or reject new company registrations below.
              </p>
            </div>
            <Button
              variant="outline"
              size="sm"
              className="ml-auto shrink-0"
              onClick={() => setStatusFilter(pendingCount > 0 ? "pending" : "draft")}
            >
              Show pending
            </Button>
          </CardContent>
        </Card>
      )}

      {showForm && (
        <Card className="mb-6">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle>{editing ? "Edit Company" : "Add Company"}</CardTitle>
            <Button variant="ghost" size="sm" onClick={resetForm}><X className="h-4 w-4" /></Button>
          </CardHeader>
          <CardContent>
            <form onSubmit={(e) => { e.preventDefault(); saveMutation.mutate(form); }} className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Company Name</Label>
                  <Input value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} required />
                </div>
                <div className="space-y-2">
                  <Label>Registration Number</Label>
                  <Input value={form.registration_number} onChange={(e) => setForm((f) => ({ ...f, registration_number: e.target.value }))} />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>VAT Number</Label>
                  <Input value={form.vat_number} onChange={(e) => setForm((f) => ({ ...f, vat_number: e.target.value }))} />
                </div>
                <div className="space-y-2">
                  <Label>Contact Phone</Label>
                  <Input value={form.contact_phone} onChange={(e) => setForm((f) => ({ ...f, contact_phone: e.target.value }))} />
                </div>
              </div>
              <div className="space-y-2">
                <Label>Company Address</Label>
                <Textarea value={form.address} onChange={(e) => setForm((f) => ({ ...f, address: e.target.value }))} rows={3} />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Account Admin Holder Name</Label>
                  <Input value={form.account_admin_name} onChange={(e) => setForm((f) => ({ ...f, account_admin_name: e.target.value }))} />
                </div>
                <div className="space-y-2">
                  <Label>Accounts Contact Name</Label>
                  <Input value={form.accounts_contact_name} onChange={(e) => setForm((f) => ({ ...f, accounts_contact_name: e.target.value }))} />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Accounts Contact Email</Label>
                  <Input type="email" value={form.accounts_contact_email} onChange={(e) => setForm((f) => ({ ...f, accounts_contact_email: e.target.value }))} />
                </div>
                <div className="space-y-2">
                  <Label>Contact Email</Label>
                  <Input type="email" value={form.contact_email} onChange={(e) => setForm((f) => ({ ...f, contact_email: e.target.value }))} />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Status</Label>
                  <Select value={form.status} onValueChange={(v) => setForm((f) => ({ ...f, status: v }))}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="draft">Draft</SelectItem>
                      <SelectItem value="pending">Pending</SelectItem>
                      <SelectItem value="approved">Approved</SelectItem>
                      <SelectItem value="suspended">Suspended</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>Payment Terms (days)</Label>
                  <IntegerField value={form.payment_terms_days} onChange={(v) => setForm((f) => ({ ...f, payment_terms_days: v }))} />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Credit Limit (£)</Label>
                  <PoundsField cents={form.credit_limit_cents} placeholder="e.g. 10000" onChange={(c) => setForm((f) => ({ ...f, credit_limit_cents: c }))} />
                </div>
                <div className="space-y-2">
                  <Label>Available Balance (£)</Label>
                  <PoundsField cents={form.credit_available_cents} placeholder="e.g. 10000" onChange={(c) => setForm((f) => ({ ...f, credit_available_cents: c }))} />
                </div>
              </div>
              <div className="space-y-2">
                <Label>Account Type</Label>
                <Select value={form.company_type} onValueChange={(v) => setForm((f) => ({ ...f, company_type: v }))}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="customer_company">Purchasing Company</SelectItem>
                    <SelectItem value="training_company">Training Company</SelectItem>
                    <SelectItem value="hybrid">Hybrid (Purchasing & Training)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Notes</Label>
                <Textarea value={form.notes} onChange={(e) => setForm((f) => ({ ...f, notes: e.target.value }))} />
              </div>
              <div className="flex gap-2">
                <Button type="submit" variant="hero" disabled={saveMutation.isPending}>
                  {saveMutation.isPending ? "Saving..." : "Save"}
                </Button>
                <Button type="button" variant="outline" onClick={resetForm}>Cancel</Button>
              </div>
            </form>
          </CardContent>
        </Card>
      )}

      {isLoading ? (
        <p className="text-muted-foreground">Loading companies...</p>
      ) : (
        <div className="bg-card border border-border rounded-xl overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Name</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Contact</TableHead>
                <TableHead>Payment Terms</TableHead>
                <TableHead className="w-[180px]">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered?.map((c) => (
                <TableRow key={c.id} className={c.status === "draft" ? "bg-amber-50/50 dark:bg-amber-950/10" : ""}>
                  <TableCell className="font-medium">
                    <button
                      className="text-primary hover:underline text-left"
                      onClick={() => router.visit(`/admin/companies/${c.id}`)}
                    >
                      {c.name}
                    </button>
                    {c.status === "draft" && (
                      <span className="block text-xs text-muted-foreground">
                        Submitted {new Date(c.created_at).toLocaleDateString()}
                      </span>
                    )}
                  </TableCell>
                  <TableCell>{typeLabel(c.company_type)}</TableCell>
                  <TableCell>
                    <Badge variant={statusColor(c.status) as any} className="capitalize">{c.status}</Badge>
                  </TableCell>
                  <TableCell>
                    <div className="text-sm">{c.contact_email || "—"}</div>
                    <div className="text-xs text-muted-foreground">{c.contact_phone || ""}</div>
                  </TableCell>
                  <TableCell>{c.payment_terms_days} days</TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      {(c.status === "draft" || c.status === "pending") && (
                        <>
                          <Button
                            variant="ghost"
                            size="sm"
                            title="Approve"
                            onClick={() => approveMutation.mutate(c.id)}
                            disabled={approveMutation.isPending}
                          >
                            <CheckCircle2 className="h-4 w-4 text-emerald-600" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            title="Reject"
                            onClick={() => rejectMutation.mutate(c.id)}
                            disabled={rejectMutation.isPending}
                          >
                            <XCircle className="h-4 w-4 text-destructive" />
                          </Button>
                        </>
                      )}
                      <Button variant="ghost" size="sm" title="Edit company" onClick={() => router.visit(`/admin/companies/${c.id}`)}><Pencil className="h-3 w-3" /></Button>
                      <Button variant="ghost" size="sm" onClick={() => deleteMutation.mutate(c.id)}><Trash2 className="h-3 w-3 text-destructive" /></Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
              {filtered?.length === 0 && (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-muted-foreground py-8">No companies found.</TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      )}
    </div>
  );
};

CompaniesPage.layout = (page: ReactNode) => <AdminLayout>{page}</AdminLayout>;

export default CompaniesPage;
