import { useEffect, useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { PoundsField, IntegerField } from "@/components/ui/number-field";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Save, KeyRound, Pencil, Loader2, ShieldAlert } from "lucide-react";
import { EditUserDialog, ResetPasswordDialog } from "@/components/admin/UserAccountDialogs";
import { useAuth } from "@/hooks/useAuth";

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

interface Props {
  companyId: string;
}

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

type CompanyUser = {
  user_id: string;
  full_name: string | null;
  email: string;
  email_verified_at: string | null;
  created_at: string;
  role: string;
  role_id: string;
};

const roleLabel = (r: string) =>
  r.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());

const CompanyDetailsTab = ({ companyId }: Props) => {
  const queryClient = useQueryClient();
  const { hasRole, isSysLevel } = useAuth();
  // Company managers viewing their own company get a self-service view: they can
  // edit profile details but not status/credit/terms (those are provider-controlled).
  const isManager = hasRole("company_manager") && !isSysLevel();
  const [form, setForm] = useState<Partial<Company>>({});

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

  useEffect(() => {
    if (company) setForm(company);
  }, [company]);

  const dirty = company
    ? Object.keys(form).some((k) => (form as any)[k] !== (company as any)[k])
    : false;

  const saveMutation = useMutation({
    mutationFn: async (payload: Partial<Company>) => {
      // Managers save via the self-service endpoint (own company, safe fields
      // only); staff use the full admin endpoint.
      const url = isManager
        ? `/api/training-companies/${companyId}`
        : `/api/admin/training-companies/${companyId}`;
      const res = await fetch(url, {
        method: "PATCH",
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
        body: JSON.stringify(payload),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.message || `Save failed (${res.status})`);
      }
      return res.json();
    },
    onSuccess: () => {
      toast.success("Company details saved");
      queryClient.invalidateQueries({ queryKey: ["admin-company", companyId] });
      queryClient.invalidateQueries({ queryKey: ["company", companyId] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const handleField = <K extends keyof Company>(key: K, value: Company[K]) =>
    setForm((f) => ({ ...f, [key]: value }));

  const handleSave = () => {
    const { id: _id, ...rest } = form;
    if (isManager) {
      // Never send provider-controlled fields from the manager view.
      const { status, company_type, payment_terms_days, credit_limit_cents, credit_available_cents, notes, ...safe } = rest as Partial<Company>;
      saveMutation.mutate(safe);
    } else {
      saveMutation.mutate(rest);
    }
  };

  if (isLoading || !company) {
    return <p className="text-sm text-muted-foreground">Loading…</p>;
  }

  return (
    <div className="space-y-6">
      <div className="bg-card border border-border rounded-xl p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-base font-semibold text-foreground">Company details</h2>
          <Button onClick={handleSave} disabled={!dirty || saveMutation.isPending} size="sm">
            {saveMutation.isPending ? (
              <Loader2 className="h-4 w-4 mr-1.5 animate-spin" />
            ) : (
              <Save className="h-4 w-4 mr-1.5" />
            )}
            Save changes
          </Button>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="md:col-span-2">
            <Label htmlFor="name">Company name</Label>
            <Input id="name" value={form.name ?? ""} onChange={(e) => handleField("name", e.target.value)} />
          </div>

          <div>
            <Label htmlFor="contact_email">Contact email</Label>
            <Input id="contact_email" type="email" value={form.contact_email ?? ""} onChange={(e) => handleField("contact_email", e.target.value)} />
          </div>
          <div>
            <Label htmlFor="contact_phone">Contact phone</Label>
            <Input id="contact_phone" value={form.contact_phone ?? ""} onChange={(e) => handleField("contact_phone", e.target.value)} />
          </div>

          <div className="md:col-span-2">
            <Label htmlFor="address">Address</Label>
            <Textarea id="address" rows={3} value={form.address ?? ""} onChange={(e) => handleField("address", e.target.value)} />
          </div>

          <div>
            <Label htmlFor="registration_number">Company registration #</Label>
            <Input id="registration_number" value={form.registration_number ?? ""} onChange={(e) => handleField("registration_number", e.target.value)} />
          </div>
          <div>
            <Label htmlFor="vat_number">VAT number</Label>
            <Input id="vat_number" value={form.vat_number ?? ""} onChange={(e) => handleField("vat_number", e.target.value)} />
          </div>

          <div>
            <Label htmlFor="account_admin_name">Account admin name</Label>
            <Input id="account_admin_name" value={form.account_admin_name ?? ""} onChange={(e) => handleField("account_admin_name", e.target.value)} />
          </div>
          <div>
            <Label htmlFor="accounts_contact_name">Accounts contact name</Label>
            <Input id="accounts_contact_name" value={form.accounts_contact_name ?? ""} onChange={(e) => handleField("accounts_contact_name", e.target.value)} />
          </div>

          <div className="md:col-span-2">
            <Label htmlFor="accounts_contact_email">Accounts contact email</Label>
            <Input id="accounts_contact_email" type="email" value={form.accounts_contact_email ?? ""} onChange={(e) => handleField("accounts_contact_email", e.target.value)} />
          </div>

          {!isManager && (
            <>
              <div>
                <Label htmlFor="status">Status</Label>
                <Select value={form.status ?? "pending"} onValueChange={(v) => handleField("status", v)}>
                  <SelectTrigger id="status"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="pending">Pending</SelectItem>
                    <SelectItem value="approved">Approved</SelectItem>
                    <SelectItem value="suspended">Suspended</SelectItem>
                    <SelectItem value="rejected">Rejected</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor="company_type">Account Type</Label>
                <Select value={form.company_type ?? "customer_company"} onValueChange={(v) => handleField("company_type", v)}>
                  <SelectTrigger id="company_type"><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>
                <Label htmlFor="payment_terms_days">Payment terms (days)</Label>
                <IntegerField id="payment_terms_days" value={form.payment_terms_days ?? 30} onChange={(v) => handleField("payment_terms_days", v)} />
              </div>
              <div>
                <Label htmlFor="credit_limit_pounds">Credit limit (£)</Label>
                <PoundsField id="credit_limit_pounds" cents={form.credit_limit_cents ?? 0} onChange={(c) => handleField("credit_limit_cents", c)} />
              </div>
              <div>
                <Label htmlFor="credit_available_pounds">Available balance (£)</Label>
                <PoundsField id="credit_available_pounds" cents={form.credit_available_cents ?? 0} onChange={(c) => handleField("credit_available_cents", c)} />
              </div>

              <div className="md:col-span-2">
                <Label htmlFor="notes">Internal notes</Label>
                <Textarea id="notes" rows={4} value={form.notes ?? ""} onChange={(e) => handleField("notes", e.target.value)} />
              </div>
            </>
          )}

          {isManager && (
            <div className="md:col-span-2 mt-2 pt-4 border-t border-border">
              <p className="text-xs text-muted-foreground mb-3">
                Credit, payment terms, and account status are managed by your training provider — contact support to change them.
              </p>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-4 text-sm">
                <div>
                  <p className="text-xs text-muted-foreground font-medium">Credit Limit</p>
                  <p className="text-foreground">£{(((company.credit_limit_cents ?? 0)) / 100).toFixed(2)}</p>
                </div>
                <div>
                  <p className="text-xs text-muted-foreground font-medium">Payment Terms</p>
                  <p className="text-foreground">{company.payment_terms_days ?? 30} days</p>
                </div>
                <div>
                  <p className="text-xs text-muted-foreground font-medium">Status</p>
                  <Badge variant={company.status === "approved" ? "default" : "secondary"} className="capitalize">{company.status}</Badge>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {!isManager && <CompanyLoginAccounts companyId={companyId} />}
    </div>
  );
};

const CompanyLoginAccounts = ({ companyId }: { companyId: string }) => {
  const queryClient = useQueryClient();
  const [editing, setEditing] = useState<CompanyUser | null>(null);
  const [resetting, setResetting] = useState<CompanyUser | null>(null);

  const { data: users, isLoading } = useQuery({
    queryKey: ["company-users", companyId],
    queryFn: async (): Promise<CompanyUser[]> => {
      const res = await fetch(`/api/admin/companies/${companyId}/users`);
      if (!res.ok) return [];
      return res.json();
    },
  });

  return (
    <div className="bg-card border border-border rounded-xl p-6">
      <div className="flex items-center justify-between mb-4">
        <div>
          <h2 className="text-base font-semibold text-foreground">Login accounts</h2>
          <p className="text-xs text-muted-foreground">
            User accounts that can sign in for this company. To invite new users, use{" "}
            <a href="/admin/user-roles" className="text-primary underline">User Roles</a>.
          </p>
        </div>
      </div>

      {isLoading ? (
        <p className="text-sm text-muted-foreground">Loading…</p>
      ) : !users?.length ? (
        <p className="text-sm text-muted-foreground italic">No login accounts linked to this company.</p>
      ) : (
        <div className="space-y-2">
          {users.map((u) => (
            <div key={u.role_id} className="flex items-center justify-between gap-3 p-3 border border-border rounded-lg">
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2 flex-wrap">
                  <p className="text-sm font-medium text-foreground truncate">{u.full_name || "(no name)"}</p>
                  <Badge variant="secondary" className="text-[10px]">{roleLabel(u.role)}</Badge>
                  {!u.email_verified_at && (
                    <Badge variant="outline" className="text-[10px] border-amber-300 text-amber-700">
                      <ShieldAlert className="h-2.5 w-2.5 mr-1" /> unverified
                    </Badge>
                  )}
                </div>
                <p className="text-xs text-muted-foreground truncate">{u.email}</p>
              </div>
              <div className="flex items-center gap-2 shrink-0">
                <Button variant="outline" size="sm" onClick={() => setEditing(u)}>
                  <Pencil className="h-3 w-3 mr-1" /> Edit
                </Button>
                <Button variant="outline" size="sm" onClick={() => setResetting(u)}>
                  <KeyRound className="h-3 w-3 mr-1" /> Set password
                </Button>
              </div>
            </div>
          ))}
        </div>
      )}

      <EditUserDialog
        user={editing}
        onClose={() => setEditing(null)}
        onSaved={() => {
          queryClient.invalidateQueries({ queryKey: ["company-users", companyId] });
          setEditing(null);
        }}
      />
      <ResetPasswordDialog
        user={resetting}
        onClose={() => setResetting(null)}
      />
    </div>
  );
};

export default CompanyDetailsTab;
