"use client"

import Link from "next/link"
import { OrgSettingsSection } from "@/components/admin/settings/org-settings-form"
import { useOrgSettingsStore } from "@/lib/admin-settings/org-settings-store"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"

export function StorageQuotasSection() {
  const storageQuotas = useOrgSettingsStore((s) => s.storageQuotas)
  const setStorageQuotas = useOrgSettingsStore((s) => s.setStorageQuotas)

  return (
    <OrgSettingsSection
      title="Quotas de stockage"
      description="Limites par défaut appliquées aux nouveaux comptes (mail, drive, photos)."
      policySection="storage_quotas"
    >
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-sm font-medium">Quotas par défaut</CardTitle>
          <CardDescription>
            Les quotas individuels se gèrent depuis la fiche utilisateur.
          </CardDescription>
        </CardHeader>
        <CardContent className="grid gap-4 sm:grid-cols-3">
          <QuotaInput
            label="Mail (Go)"
            value={storageQuotas.default_mail_gib}
            onChange={(v) => setStorageQuotas({ default_mail_gib: v })}
          />
          <QuotaInput
            label="Drive (Go)"
            value={storageQuotas.default_drive_gib}
            onChange={(v) => setStorageQuotas({ default_drive_gib: v })}
          />
          <QuotaInput
            label="Photos (Go)"
            value={storageQuotas.default_photos_gib}
            onChange={(v) => setStorageQuotas({ default_photos_gib: v })}
          />
          <div className="sm:col-span-3">
            <Label>Seuil d&apos;alerte (%)</Label>
            <Input
              className="mt-1 h-9 max-w-xs"
              type="number"
              min={50}
              max={100}
              value={storageQuotas.warn_threshold_pct}
              onChange={(e) =>
                setStorageQuotas({ warn_threshold_pct: Number(e.target.value) || 90 })
              }
            />
          </div>
        </CardContent>
      </Card>

      <Button asChild variant="outline" size="sm">
        <Link href="/admin/settings/users">Gérer les quotas par utilisateur</Link>
      </Button>
    </OrgSettingsSection>
  )
}

function QuotaInput({
  label,
  value,
  onChange,
}: {
  label: string
  value: number
  onChange: (v: number) => void
}) {
  return (
    <div>
      <Label>{label}</Label>
      <Input
        className="mt-1 h-9"
        type="number"
        min={0}
        step={0.5}
        value={value}
        onChange={(e) => onChange(Number(e.target.value) || 0)}
      />
    </div>
  )
}
