"use client"

import { useEffect, useState } from "react"
import { OrgSettingsSection } from "@/components/admin/settings/org-settings-form"
import { AdminSettingsCard } from "@/components/admin/settings/admin-settings-card"
import { FieldGroup } from "@/components/admin/settings/field-group"
import { AutomationTabMasonry } from "@/components/gmail/settings/automation/automation-tab-masonry"
import { useOrgSettingsStore } from "@/lib/admin-settings/org-settings-store"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Textarea } from "@/components/ui/textarea"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { DriveOrgFoldersSection } from "@/components/admin/settings/sections/drive-org-section"
import { DriveOrgWebDAVSection } from "@/components/admin/settings/sections/drive-org-webdav-section"
import { DriveMountOAuthSection } from "@/components/admin/settings/sections/drive-mount-oauth-section"

export function FilePoliciesSection() {
  const filePolicies = useOrgSettingsStore((s) => s.filePolicies)
  const setFilePolicies = useOrgSettingsStore((s) => s.setFilePolicies)
  const [mountOAuthDraft, setMountOAuthDraft] = useState(filePolicies.mount_oauth)
  const vtKeyConfigured = useOrgSettingsStore(
    (s) => s.meta?.secrets?.virustotal_api_key?.configured ?? false
  )
  const vtKeyMissing =
    filePolicies.virus_scan_enabled &&
    !vtKeyConfigured &&
    !(filePolicies.virustotal_api_key ?? "").trim()

  useEffect(() => {
    setMountOAuthDraft(filePolicies.mount_oauth)
  }, [filePolicies.mount_oauth])

  return (
    <OrgSettingsSection
      title="Politiques fichiers"
      description="Règles d'upload, partage externe et rétention pour UltiDrive."
      policySection="file_policies"
      beforeSave={() => setFilePolicies({ mount_oauth: mountOAuthDraft })}
    >
      <AutomationTabMasonry columns={2}>
        <AdminSettingsCard
          title="Politiques UltiDrive"
          description="Limites d'upload, partage externe, extensions et analyse antivirus."
        >
          <div className="grid min-w-0 gap-4">
            <FieldGroup>
              <Label>Taille max upload (Mo)</Label>
              <Input
                className="h-9"
                type="number"
                min={1}
                value={filePolicies.max_upload_mib}
                onChange={(e) =>
                  setFilePolicies({ max_upload_mib: Number(e.target.value) || 1 })
                }
              />
            </FieldGroup>
            <FieldGroup>
              <Label>Expiration liens par défaut (jours)</Label>
              <Input
                className="h-9"
                type="number"
                min={1}
                value={filePolicies.default_link_expiry_days}
                onChange={(e) =>
                  setFilePolicies({
                    default_link_expiry_days: Number(e.target.value) || 1,
                  })
                }
              />
            </FieldGroup>
            <FieldGroup>
              <Label>Rétention corbeille (jours)</Label>
              <Input
                className="h-9"
                type="number"
                min={1}
                value={filePolicies.retention_trash_days}
                onChange={(e) =>
                  setFilePolicies({ retention_trash_days: Number(e.target.value) || 1 })
                }
              />
            </FieldGroup>
            <FieldGroup>
              <Label>Partage externe</Label>
              <Select
                value={filePolicies.external_sharing}
                onValueChange={(external_sharing) =>
                  setFilePolicies({
                    external_sharing: external_sharing as typeof filePolicies.external_sharing,
                  })
                }
              >
                <SelectTrigger className="h-9 w-full min-w-0">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="disabled">Désactivé</SelectItem>
                  <SelectItem value="authenticated">Utilisateurs authentifiés</SelectItem>
                  <SelectItem value="public_link">Liens publics autorisés</SelectItem>
                </SelectContent>
              </Select>
            </FieldGroup>
            <FieldGroup>
              <Label>Extensions autorisées (vide = toutes)</Label>
              <Textarea
                className="min-h-[80px] font-mono text-xs"
                value={filePolicies.allowed_extensions}
                onChange={(e) => setFilePolicies({ allowed_extensions: e.target.value })}
                placeholder="pdf, docx, png, jpg"
              />
            </FieldGroup>
          </div>

          <label className="flex items-center justify-between gap-4 rounded-lg border p-3">
            <FieldGroup>
              <p className="text-sm font-medium">Bloquer les exécutables</p>
              <p className="text-xs text-muted-foreground">exe, bat, sh, app, etc.</p>
            </FieldGroup>
            <Switch
              checked={filePolicies.block_executable}
              onCheckedChange={(block_executable) => setFilePolicies({ block_executable })}
            />
          </label>

          <label className="flex items-center justify-between gap-4 rounded-lg border p-3">
            <FieldGroup>
              <p className="text-sm font-medium">Analyse antivirus à l&apos;upload</p>
              <p className="text-xs text-muted-foreground">
                VirusTotal — scan synchrone à l&apos;upload Drive et pièces jointes mail
              </p>
            </FieldGroup>
            <Switch
              checked={filePolicies.virus_scan_enabled}
              onCheckedChange={(virus_scan_enabled) => setFilePolicies({ virus_scan_enabled })}
            />
          </label>

          {filePolicies.virus_scan_enabled ? (
            <FieldGroup>
              <Label>Clé API VirusTotal</Label>
              <Input
                className="h-9"
                type="password"
                autoComplete="off"
                value={filePolicies.virustotal_api_key ?? ""}
                onChange={(e) => setFilePolicies({ virustotal_api_key: e.target.value })}
                placeholder={
                  vtKeyConfigured ? "•••••••• (laisser vide pour conserver)" : "Coller la clé API"
                }
              />
              {vtKeyConfigured && !(filePolicies.virustotal_api_key ?? "").trim() ? (
                <p className="text-xs text-muted-foreground">Clé configurée</p>
              ) : null}
              {vtKeyMissing ? (
                <p className="text-xs text-amber-600 dark:text-amber-500">
                  Analyse activée sans clé API — les uploads ne seront pas scannés.
                </p>
              ) : null}
            </FieldGroup>
          ) : null}
        </AdminSettingsCard>

        <AdminSettingsCard
          title="Connexion cloud (OAuth)"
          description="Permet aux utilisateurs de monter Google Drive, Dropbox ou OneDrive depuis UltiDrive."
        >
          <DriveMountOAuthSection draft={mountOAuthDraft} onChange={setMountOAuthDraft} embedded />
        </AdminSettingsCard>

        <AdminSettingsCard
          title="Montages WebDAV d'organisation"
          description="Serveur WebDAV partagé (NAS, Nextcloud externe) visible par tous les utilisateurs UltiDrive."
        >
          <DriveOrgWebDAVSection embedded />
        </AdminSettingsCard>

        <AdminSettingsCard
          title="Dossiers d'organisation"
          description="Espaces de stockage internes (group folders Nextcloud) liés aux organisations Authentik."
        >
          <DriveOrgFoldersSection embedded />
        </AdminSettingsCard>
      </AutomationTabMasonry>
    </OrgSettingsSection>
  )
}
