"use client";

import { Boxes, Building2, CalendarDays, Gauge, Lock, SlidersHorizontal, Users } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { FieldGroup } from "@/components/ui/field";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import { FormErrorAlert, TextField } from "@/components/app/form-fields";
import { SectionCard, StatCard } from "@/components/app/page";
import { Card } from "@/components/ui/card";
import { ErrorState } from "../../components/ui/page-states";
import StatusBadge from "../../components/ui/status-badge";
import { formatDate, humanize } from "../../lib/format";
import { ReadOnlyField, SettingsLayout, UnsavedHint } from "../settings-layout";
import { useOrganizationSettings } from "../useSettings";

export function OrganizationSettingsPage() {
  const { organization, error, isLoading, retry, form, submit, setMaterialFollowup, featurePending } = useOrganizationSettings();
  const materials = Boolean(organization?.features?.materialFollowup);
  const kept = organization?.materialCheckpointsCount || 0;
  const { isDirty, isSubmitting } = form.formState;

  return <SettingsLayout title="Organization" description="Your buying house workspace. Everything inside it is private to your organization.">
    {isLoading && !organization && <>
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">{Array.from({ length: 4 }).map((_, index) => <Skeleton key={index} className="h-24 rounded-xl" />)}</div>
      <Skeleton className="h-72 rounded-xl" />
    </>}
    {!isLoading && error && <Card className="py-0"><ErrorState error={error} onRetry={retry} /></Card>}
    {organization && !error && <>
      <section className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4" aria-label="Organization summary">
        <StatCard label="Plan" icon={Gauge} value={`${humanize(organization.plan)}`} hint="Managed by the platform team" />
        <StatCard label="Status" icon={Building2} value={<StatusBadge status={organization.status} className="text-sm" />} hint="Workspace account status" />
        <StatCard label="Members" icon={Users} value={`${organization.activeUsersCount} / ${organization.usersCount}`} hint="Active / total accounts" />
        <StatCard label="Created" icon={CalendarDays} value={formatDate(organization.createdAt)} hint="Workspace sign-up date" />
      </section>

      <form onSubmit={submit} noValidate>
        <SectionCard
          title="Organization profile"
          icon={Building2}
          description="The name shows in the sidebar and to everyone in your workspace."
          actions={!organization.canManage && <Badge variant="outline"><Lock /> Only organization admins can edit</Badge>}
        >
          <div className="grid gap-5">
            <FormErrorAlert form={form} />
            <FieldGroup className="grid gap-5 sm:grid-cols-2">
              {organization.canManage
                ? <TextField control={form.control} name="name" label="Organization name" description="Shown in the sidebar and to your team." />
                : <ReadOnlyField id="org-name" label="Organization name" value={organization.name} />}
              <ReadOnlyField id="org-slug" label="Workspace ID" value={organization.slug} description="Stable identifier for support requests." />
              <ReadOnlyField id="org-owner" label="Owner" value={organization.owner ? `${organization.owner.name} · ${organization.owner.email}` : "Not set"} description="The owner keeps admin access and cannot be deactivated." />
              <ReadOnlyField id="org-plan" label="Plan" value={`${humanize(organization.plan)} plan`} description="Plans and billing are managed by the platform team." />
            </FieldGroup>
            {organization.canManage && <div className="flex flex-wrap items-center justify-end gap-3 border-t pt-4">
              <UnsavedHint show={isDirty} />
              {isDirty && <Button type="button" variant="outline" disabled={isSubmitting} onClick={() => form.reset({ name: organization.name || "" })}>Discard</Button>}
              <Button type="submit" disabled={isSubmitting || !isDirty}>{isSubmitting && <Spinner />} Save organization</Button>
            </div>}
          </div>
        </SectionCard>
      </form>

      <SectionCard
        id="features"
        title="Features"
        icon={SlidersHorizontal}
        description="Optional parts of the workspace. Switch on only what your house actually uses, so screens stay simple."
        actions={!organization.canManage && <Badge variant="outline"><Lock /> Only organization admins can edit</Badge>}
      >
        <div className="flex items-start justify-between gap-4 rounded-lg border p-4">
          <div className="grid min-w-0 gap-1">
            <Label htmlFor="feature-material-followup" className="flex flex-wrap items-center gap-2 text-sm font-medium">
              <Boxes className="size-4 text-muted-foreground" aria-hidden="true" /> Material follow-up
              <Badge variant={materials ? "success" : "outline"}>{materials ? "On" : "Off"}</Badge>
            </Label>
            <p className="text-sm text-muted-foreground">
              A buying house does not buy or store fabric and trims; the factory does. Most houses only watch the in-house dates, and the time &amp; action milestones (&quot;Fabric in-house&quot;, &quot;Trims in-house&quot;) already cover that.
              Switch this on only if your team keeps its own register of fabric and trims per order: supplier, booking, promised and actual arrival, shortages.
            </p>
            <p className="text-xs text-muted-foreground">
              {materials
                ? "On: purchase orders have a Materials section, and open materials count for production readiness, order health, the worklist, the dashboard, and the factory portal."
                : `Off: no Materials section anywhere, and materials never block production readiness.${kept ? ` ${kept} saved material ${kept === 1 ? "checkpoint is" : "checkpoints are"} kept and come back when you switch it on.` : ""}`}
            </p>
          </div>
          <div className="flex shrink-0 items-center gap-2 pt-0.5">
            {featurePending && <Spinner className="size-4" />}
            <Switch id="feature-material-followup" checked={materials} disabled={!organization.canManage || featurePending} onCheckedChange={setMaterialFollowup} aria-label="Material follow-up" />
          </div>
        </div>
      </SectionCard>
    </>}
  </SettingsLayout>;
}
