"use client";

import { useState, useEffect } from "react";
import { useSession } from "next-auth/react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
  User, Shield, Users, Building2,
  Camera, Loader2, Check, Mail, Phone,
  Plus, Trash2, Crown, Eye, EyeOff,
  Percent, Star, Pencil,
} from "lucide-react";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import {
  Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle,
} from "@/components/ui/dialog";
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { cn, getInitials } from "@/lib/utils";
import { toast } from "sonner";

// ─── Schémas ───────────────────────────────────────────────────

const profileSchema = z.object({
  name: z.string().min(2, "Le nom doit contenir au moins 2 caractères"),
  phone: z.string().optional(),
});

const organizationSchema = z.object({
  name:       z.string().min(2, "Nom requis"),
  email:      z.string().email("Email invalide").optional().or(z.literal("")),
  phone:      z.string().optional(),
  address:    z.string().optional(),
  city:       z.string().optional(),
  postalCode: z.string().optional(),
  country:    z.string().default("SN"),
  siret:      z.string().optional(),
  vatNumber:  z.string().optional(),
  ninea:      z.string().optional(),
  rccm:       z.string().optional(),
  currency:   z.string().default("XOF"),
  documentVisibility: z.object({
    siret:     z.boolean(),
    vatNumber: z.boolean(),
    ninea:     z.boolean(),
    rccm:      z.boolean(),
    phone:     z.boolean(),
    email:     z.boolean(),
    website:   z.boolean(),
    address:   z.boolean(),
  }).optional(),
});

const inviteMemberSchema = z.object({
  email: z.string().email("Email invalide"),
  role: z.enum(["ADMIN", "ACCOUNTANT", "MEMBER", "VIEWER"]),
});

type ProfileForm = z.infer<typeof profileSchema>;
type OrgForm = z.infer<typeof organizationSchema>;
type InviteForm = z.infer<typeof inviteMemberSchema>;

// ─── Types ─────────────────────────────────────────────────────

type Member = {
  id: string;
  user: {
    id: string;
    name?: string | null;
    email: string;
    image?: string | null;
  };
  role: string;
  joinedAt?: string | null;
};

type DocVisibility = {
  siret: boolean; vatNumber: boolean; ninea: boolean; rccm: boolean;
  phone: boolean; email: boolean; website: boolean; address: boolean;
};

const DEFAULT_VISIBILITY: DocVisibility = {
  siret: false, vatNumber: false, ninea: true, rccm: true,
  phone: true, email: true, website: false, address: true,
};

type OrgData = {
  id: string;
  name: string;
  email?: string | null;
  phone?: string | null;
  address?: string | null;
  city?: string | null;
  postalCode?: string | null;
  country: string;
  siret?: string | null;
  vatNumber?: string | null;
  ninea?: string | null;
  rccm?: string | null;
  currency: string;
  documentVisibility?: DocVisibility | null;
  members: Member[];
};

// ─── Config rôles ──────────────────────────────────────────────

const ROLE_CONFIG: Record<string, { label: string; color: string }> = {
  OWNER:      { label: "Propriétaire", color: "bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400" },
  ADMIN:      { label: "Admin",        color: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400" },
  ACCOUNTANT: { label: "Comptable",    color: "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400" },
  MEMBER:     { label: "Membre",       color: "bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-400" },
  VIEWER:     { label: "Lecteur",      color: "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400" },
};

// ─── Onglet Profil ─────────────────────────────────────────────

function ProfileTab({ session }: { session: any }) {
  const [isSaving, setIsSaving] = useState(false);
  const [saved, setSaved] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors, isDirty },
  } = useForm<ProfileForm>({
    resolver: zodResolver(profileSchema),
    defaultValues: {
      name: session?.user?.name ?? "",
      phone: "",
    },
  });

  const onSubmit = async (data: ProfileForm) => {
    setIsSaving(true);
    try {
      const res = await fetch("/api/users/profile", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      const json = await res.json();
      if (json.success) {
        toast.success("Profil mis à jour");
        setSaved(true);
        setTimeout(() => setSaved(false), 3000);
      } else {
        toast.error(json.error ?? "Erreur lors de la mise à jour");
      }
    } catch {
      toast.error("Erreur réseau");
    } finally {
      setIsSaving(false);
    }
  };

  const initials = getInitials(session?.user?.name ?? session?.user?.email ?? "U");

  return (
    <div className="space-y-6 max-w-xl">
      {/* Avatar */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base">Photo de profil</CardTitle>
          <CardDescription>Votre avatar visible par les membres de votre organisation</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center gap-4">
            <div className="relative">
              {session?.user?.image ? (
                <img
                  src={session.user.image}
                  alt={session.user.name ?? "Avatar"}
                  className="h-16 w-16 rounded-full object-cover"
                />
              ) : (
                <div className="h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold text-xl">
                  {initials}
                </div>
              )}
              <button className="absolute -bottom-1 -right-1 h-6 w-6 rounded-full bg-background border shadow-sm flex items-center justify-center hover:bg-muted transition-colors">
                <Camera className="h-3 w-3 text-muted-foreground" />
              </button>
            </div>
            <div>
              <p className="font-medium text-sm">{session?.user?.name ?? "Utilisateur"}</p>
              <p className="text-xs text-muted-foreground">{session?.user?.email}</p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Informations personnelles */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base">Informations personnelles</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
            <div className="space-y-1.5">
              <Label htmlFor="p-name">Nom complet</Label>
              <Input
                id="p-name"
                {...register("name")}
                placeholder="Jean Dupont"
              />
              {errors.name && (
                <p className="text-xs text-destructive">{errors.name.message}</p>
              )}
            </div>

            <div className="space-y-1.5">
              <Label htmlFor="p-email">
                Adresse email
                <Badge variant="secondary" className="ml-2 text-[10px] py-0">Non modifiable</Badge>
              </Label>
              <div className="relative">
                <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
                <Input
                  id="p-email"
                  value={session?.user?.email ?? ""}
                  disabled
                  className="pl-9 bg-muted/50 text-muted-foreground"
                />
              </div>
              <p className="text-xs text-muted-foreground">
                L&apos;email est géré via votre fournisseur d&apos;authentification.
              </p>
            </div>

            <div className="space-y-1.5">
              <Label htmlFor="p-phone">Téléphone</Label>
              <div className="relative">
                <Phone className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
                <Input
                  id="p-phone"
                  {...register("phone")}
                  placeholder="+33 6 12 34 56 78"
                  className="pl-9"
                />
              </div>
            </div>

            <div className="flex justify-end pt-2">
              <Button
                type="submit"
                size="sm"
                disabled={isSaving || !isDirty}
                className="gap-1.5 min-w-[120px]"
              >
                {isSaving ? (
                  <Loader2 className="h-3.5 w-3.5 animate-spin" />
                ) : saved ? (
                  <Check className="h-3.5 w-3.5" />
                ) : null}
                {saved ? "Enregistré !" : "Enregistrer"}
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}

// ─── Onglet Organisation ───────────────────────────────────────

function OrganizationTab({ org, onRefresh }: { org: OrgData | null; onRefresh: () => void }) {
  const [isSaving, setIsSaving] = useState(false);
  const [saved, setSaved] = useState(false);

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    formState: { errors, isDirty },
    reset,
  } = useForm<OrgForm>({
    resolver: zodResolver(organizationSchema),
    defaultValues: {
      name:       org?.name       ?? "",
      email:      org?.email      ?? "",
      phone:      org?.phone      ?? "",
      address:    org?.address    ?? "",
      city:       org?.city       ?? "",
      postalCode: org?.postalCode ?? "",
      country:    org?.country    ?? "SN",
      siret:      org?.siret      ?? "",
      vatNumber:  org?.vatNumber  ?? "",
      ninea:      org?.ninea      ?? "",
      rccm:       org?.rccm       ?? "",
      currency:   org?.currency   ?? "XOF",
      documentVisibility: org?.documentVisibility ?? DEFAULT_VISIBILITY,
    },
  });

  useEffect(() => {
    if (org) {
      reset({
        name:       org.name,
        email:      org.email      ?? "",
        phone:      org.phone      ?? "",
        address:    org.address    ?? "",
        city:       org.city       ?? "",
        postalCode: org.postalCode ?? "",
        country:    org.country,
        siret:      org.siret      ?? "",
        vatNumber:  org.vatNumber  ?? "",
        ninea:      org.ninea      ?? "",
        rccm:       org.rccm       ?? "",
        currency:   org.currency,
        documentVisibility: org.documentVisibility ?? DEFAULT_VISIBILITY,
      });
    }
  }, [org, reset]);

  const onSubmit = async (data: OrgForm) => {
    setIsSaving(true);
    try {
      const res = await fetch("/api/organizations/current", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      const json = await res.json();
      if (json.success) {
        toast.success("Organisation mise à jour");
        setSaved(true);
        setTimeout(() => setSaved(false), 3000);
        onRefresh();
      } else {
        toast.error(json.error ?? "Erreur lors de la mise à jour");
      }
    } catch {
      toast.error("Erreur réseau");
    } finally {
      setIsSaving(false);
    }
  };

  const currency = watch("currency");
  const country = watch("country");

  return (
    <div className="space-y-6 max-w-2xl">
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base">Informations de l&apos;organisation</CardTitle>
          <CardDescription>Ces informations apparaissent sur vos factures et documents</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-5">
            {/* Nom + email */}
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-1.5">
                <Label htmlFor="o-name">Nom de l&apos;entreprise <span className="text-destructive">*</span></Label>
                <Input id="o-name" {...register("name")} placeholder="Ma Société SAS" />
                {errors.name && <p className="text-xs text-destructive">{errors.name.message}</p>}
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="o-email">Email professionnel</Label>
                <Input id="o-email" {...register("email")} type="email" placeholder="contact@masociete.fr" />
                {errors.email && <p className="text-xs text-destructive">{errors.email.message}</p>}
              </div>
            </div>

            {/* Téléphone */}
            <div className="space-y-1.5">
              <Label htmlFor="o-phone">Téléphone</Label>
              <Input id="o-phone" {...register("phone")} placeholder="+33 1 23 45 67 89" />
            </div>

            <Separator />

            {/* Adresse */}
            <div className="space-y-1.5">
              <Label htmlFor="o-address">Adresse</Label>
              <Input id="o-address" {...register("address")} placeholder="12 rue de la Paix" />
            </div>
            <div className="grid gap-4 sm:grid-cols-3">
              <div className="space-y-1.5">
                <Label htmlFor="o-postal">Code postal</Label>
                <Input id="o-postal" {...register("postalCode")} placeholder="75001" />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="o-city">Ville</Label>
                <Input id="o-city" {...register("city")} placeholder="Paris" />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="o-country">Pays</Label>
                <Select value={country} onValueChange={(v) => setValue("country", v)}>
                  <SelectTrigger id="o-country">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="FR">France</SelectItem>
                    <SelectItem value="BE">Belgique</SelectItem>
                    <SelectItem value="CH">Suisse</SelectItem>
                    <SelectItem value="LU">Luxembourg</SelectItem>
                    <SelectItem value="CA">Canada</SelectItem>
                    <SelectItem value="MA">Maroc</SelectItem>
                    <SelectItem value="SN">Sénégal</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <Separator />

            {/* Identifiants légaux */}
            <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
              Identifiants légaux
            </p>
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-1.5">
                <Label htmlFor="o-ninea">NINEA</Label>
                <Input id="o-ninea" {...register("ninea")} placeholder="00000000000" className="font-mono" />
                <p className="text-[11px] text-muted-foreground">Numéro d'Identification National des Entreprises</p>
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="o-rccm">RCCM</Label>
                <Input id="o-rccm" {...register("rccm")} placeholder="SN-DKR-2024-B-00000" className="font-mono" />
                <p className="text-[11px] text-muted-foreground">Registre du Commerce et du Crédit Mobilier</p>
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="o-siret">SIRET</Label>
                <Input id="o-siret" {...register("siret")} placeholder="123 456 789 00012" className="font-mono" />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="o-vat">N° TVA</Label>
                <Input id="o-vat" {...register("vatNumber")} placeholder="FR12345678901" className="font-mono" />
              </div>
            </div>

            <div className="space-y-1.5">
              <Label>Devise par défaut</Label>
              <Select value={currency} onValueChange={(v) => setValue("currency", v)}>
                <SelectTrigger className="w-[220px]">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="XOF">F CFA — Franc CFA UEMOA (XOF)</SelectItem>
                  <SelectItem value="XAF">F CFA — Franc CFA CEMAC (XAF)</SelectItem>
                  <SelectItem value="EUR">€ Euro (EUR)</SelectItem>
                  <SelectItem value="USD">$ Dollar US (USD)</SelectItem>
                  <SelectItem value="GBP">£ Livre sterling (GBP)</SelectItem>
                  <SelectItem value="CHF">CHF Franc suisse</SelectItem>
                  <SelectItem value="CAD">$ Dollar canadien (CAD)</SelectItem>
                  <SelectItem value="MAD">MAD Dirham marocain</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <Separator />

            {/* Visibilité sur les documents */}
            <div>
              <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1">
                Informations affichées sur les documents
              </p>
              <p className="text-xs text-muted-foreground mb-4">
                Choisissez les informations à faire apparaître sur vos factures, devis et bons de livraison.
              </p>
              <div className="grid sm:grid-cols-2 gap-3">
                {([
                  { key: "ninea",      label: "NINEA",          desc: "Identifiant fiscal sénégalais" },
                  { key: "rccm",       label: "RCCM",           desc: "Registre du commerce" },
                  { key: "siret",      label: "SIRET",          desc: "Numéro SIRET France" },
                  { key: "vatNumber",  label: "N° TVA",         desc: "TVA intracommunautaire" },
                  { key: "phone",      label: "Téléphone",      desc: "Numéro de téléphone" },
                  { key: "email",      label: "Email",          desc: "Adresse email professionnelle" },
                  { key: "address",    label: "Adresse",        desc: "Adresse postale complète" },
                  { key: "website",    label: "Site web",       desc: "URL du site internet" },
                ] as { key: keyof DocVisibility; label: string; desc: string }[]).map(({ key, label, desc }) => {
                  const vis = watch("documentVisibility") ?? DEFAULT_VISIBILITY;
                  const checked = vis[key] ?? DEFAULT_VISIBILITY[key];
                  return (
                    <div key={key} className={`flex items-center justify-between rounded-lg border px-4 py-3 transition-colors ${checked ? "border-primary/40 bg-primary/5" : "bg-muted/20"}`}>
                      <div>
                        <p className="text-sm font-medium flex items-center gap-1.5">
                          {checked
                            ? <Eye className="h-3.5 w-3.5 text-primary" />
                            : <EyeOff className="h-3.5 w-3.5 text-muted-foreground" />}
                          {label}
                        </p>
                        <p className="text-xs text-muted-foreground">{desc}</p>
                      </div>
                      <Switch
                        checked={checked}
                        onCheckedChange={(val) =>
                          setValue("documentVisibility", { ...vis, [key]: val }, { shouldDirty: true })
                        }
                      />
                    </div>
                  );
                })}
              </div>
            </div>

            <div className="flex justify-end pt-2">
              <Button
                type="submit"
                size="sm"
                disabled={isSaving || !isDirty}
                className="gap-1.5 min-w-[140px]"
              >
                {isSaving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : saved ? <Check className="h-3.5 w-3.5" /> : null}
                {saved ? "Enregistré !" : "Sauvegarder"}
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}

// ─── Onglet Membres ────────────────────────────────────────────

function MembersTab({ members, onRefresh }: { members: Member[]; onRefresh: () => void }) {
  const [showInvite, setShowInvite] = useState(false);
  const [isInviting, setIsInviting] = useState(false);
  const [removingId, setRemovingId] = useState<string | null>(null);
  const { data: session } = useSession();

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    reset,
    formState: { errors },
  } = useForm<InviteForm>({
    resolver: zodResolver(inviteMemberSchema),
    defaultValues: { email: "", role: "MEMBER" },
  });

  const role = watch("role");

  const onInvite = async (data: InviteForm) => {
    setIsInviting(true);
    try {
      const res = await fetch("/api/organizations/current/members", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      const json = await res.json();
      if (json.success) {
        toast.success(`Invitation envoyée à ${data.email}`);
        setShowInvite(false);
        reset();
        onRefresh();
      } else {
        toast.error(json.error ?? "Erreur lors de l'invitation");
      }
    } catch {
      toast.error("Erreur réseau");
    } finally {
      setIsInviting(false);
    }
  };

  const handleRemove = async (memberId: string) => {
    try {
      const res = await fetch(`/api/organizations/current/members/${memberId}`, {
        method: "DELETE",
      });
      const json = await res.json();
      if (json.success) {
        toast.success("Membre retiré de l'organisation");
        onRefresh();
      } else {
        toast.error(json.error ?? "Erreur lors de la suppression");
      }
    } catch {
      toast.error("Erreur réseau");
    } finally {
      setRemovingId(null);
    }
  };

  return (
    <div className="space-y-6 max-w-2xl">
      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="text-base">Membres de l&apos;organisation</CardTitle>
              <CardDescription className="mt-0.5">
                {members.length} membre{members.length !== 1 ? "s" : ""} au total
              </CardDescription>
            </div>
            <Button size="sm" className="gap-1.5" onClick={() => setShowInvite(true)}>
              <Plus className="h-3.5 w-3.5" />
              Inviter un membre
            </Button>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          {members.length === 0 ? (
            <div className="text-center py-10 text-sm text-muted-foreground">
              Aucun membre pour le moment
            </div>
          ) : (
            <div className="divide-y">
              {members.map((member) => {
                const cfg = ROLE_CONFIG[member.role] ?? ROLE_CONFIG.MEMBER;
                const isCurrentUser = member.user.id === session?.user?.id;
                const initials = getInitials(member.user.name ?? member.user.email);

                return (
                  <div
                    key={member.id}
                    className="flex items-center justify-between px-6 py-3 hover:bg-muted/20 transition-colors"
                  >
                    <div className="flex items-center gap-3">
                      {member.user.image ? (
                        <img
                          src={member.user.image}
                          alt={member.user.name ?? "Avatar"}
                          className="h-9 w-9 rounded-full object-cover"
                        />
                      ) : (
                        <div className="h-9 w-9 rounded-full bg-primary/10 flex items-center justify-center text-primary text-xs font-bold">
                          {initials}
                        </div>
                      )}
                      <div>
                        <div className="flex items-center gap-2">
                          <p className="text-sm font-medium">
                            {member.user.name ?? member.user.email}
                          </p>
                          {isCurrentUser && (
                            <Badge variant="secondary" className="text-[10px] py-0">Vous</Badge>
                          )}
                        </div>
                        <p className="text-xs text-muted-foreground">{member.user.email}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      <span className={cn(
                        "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",
                        cfg.color
                      )}>
                        {member.role === "OWNER" && <Crown className="h-3 w-3 mr-1" />}
                        {cfg.label}
                      </span>
                      {!isCurrentUser && member.role !== "OWNER" && (
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 text-muted-foreground hover:text-destructive"
                          onClick={() => setRemovingId(member.id)}
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                        </Button>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Modal invitation */}
      <Dialog open={showInvite} onOpenChange={setShowInvite}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Inviter un membre</DialogTitle>
            <DialogDescription>
              Un email d&apos;invitation sera envoyé à l&apos;adresse indiquée.
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={handleSubmit(onInvite)} className="space-y-4 py-2">
            <div className="space-y-1.5">
              <Label htmlFor="inv-email">Adresse email</Label>
              <Input
                id="inv-email"
                type="email"
                {...register("email")}
                placeholder="colleague@exemple.fr"
              />
              {errors.email && <p className="text-xs text-destructive">{errors.email.message}</p>}
            </div>
            <div className="space-y-1.5">
              <Label>Rôle</Label>
              <Select value={role} onValueChange={(v) => setValue("role", v as InviteForm["role"])}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="ADMIN">Admin — Accès complet</SelectItem>
                  <SelectItem value="ACCOUNTANT">Comptable — Lecture/écriture</SelectItem>
                  <SelectItem value="MEMBER">Membre — Accès standard</SelectItem>
                  <SelectItem value="VIEWER">Lecteur — Lecture seule</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <DialogFooter>
              <Button variant="outline" type="button" onClick={() => setShowInvite(false)}>
                Annuler
              </Button>
              <Button type="submit" disabled={isInviting} className="gap-1.5">
                {isInviting && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
                Envoyer l&apos;invitation
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* Confirmation suppression */}
      <AlertDialog open={!!removingId} onOpenChange={() => setRemovingId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Retirer ce membre ?</AlertDialogTitle>
            <AlertDialogDescription>
              Ce membre perdra immédiatement accès à l&apos;organisation et toutes ses données associées.
              Cette action est irréversible.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Annuler</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive hover:bg-destructive/90"
              onClick={() => removingId && handleRemove(removingId)}
            >
              Retirer le membre
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}

// ─── Onglet Sécurité ───────────────────────────────────────────

function SecurityTab() {
  const [showPasswordModal, setShowPasswordModal] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");

  const handleChangePassword = async () => {
    if (newPassword !== confirmPassword) {
      toast.error("Les mots de passe ne correspondent pas");
      return;
    }
    if (newPassword.length < 8) {
      toast.error("Le mot de passe doit contenir au moins 8 caractères");
      return;
    }
    setIsLoading(true);
    try {
      const res = await fetch("/api/users/change-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ currentPassword, newPassword }),
      });
      const json = await res.json();
      if (json.success) {
        toast.success("Mot de passe modifié avec succès");
        setShowPasswordModal(false);
        setCurrentPassword("");
        setNewPassword("");
        setConfirmPassword("");
      } else {
        toast.error(json.error ?? "Erreur lors du changement de mot de passe");
      }
    } catch {
      toast.error("Erreur réseau");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="space-y-6 max-w-xl">
      {/* Mot de passe */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base">Mot de passe</CardTitle>
          <CardDescription>Modifiez votre mot de passe de connexion</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between py-2">
            <div>
              <p className="text-sm font-medium">Mot de passe actuel</p>
              <p className="text-xs text-muted-foreground mt-0.5">
                Dernière modification : jamais
              </p>
            </div>
            <Button variant="outline" size="sm" onClick={() => setShowPasswordModal(true)}>
              Modifier
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Sessions */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base">Sessions actives</CardTitle>
          <CardDescription>Appareils connectés à votre compte</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between py-2">
            <div>
              <p className="text-sm font-medium">Navigateur actuel</p>
              <p className="text-xs text-muted-foreground mt-0.5">Session en cours</p>
            </div>
            <Badge variant="secondary" className="text-xs">Active</Badge>
          </div>
          <Separator className="my-3" />
          <Button
            variant="outline"
            size="sm"
            className="text-destructive hover:bg-destructive/10 hover:text-destructive"
            onClick={() => toast.info("Fonctionnalité à venir")}
          >
            Déconnecter toutes les autres sessions
          </Button>
        </CardContent>
      </Card>

      {/* Zone de danger */}
      <Card className="border-destructive/30">
        <CardHeader className="pb-3">
          <CardTitle className="text-base text-destructive">Zone de danger</CardTitle>
          <CardDescription>Ces actions sont irréversibles, procédez avec précaution</CardDescription>
        </CardHeader>
        <CardContent>
          <Button
            variant="outline"
            size="sm"
            className="text-destructive border-destructive/30 hover:bg-destructive/10 hover:text-destructive"
            onClick={() => toast.error("Contactez le support pour supprimer votre compte")}
          >
            Supprimer mon compte
          </Button>
        </CardContent>
      </Card>

      {/* Modal changement mdp */}
      <Dialog open={showPasswordModal} onOpenChange={setShowPasswordModal}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Changer le mot de passe</DialogTitle>
            <DialogDescription>
              Votre nouveau mot de passe doit contenir au moins 8 caractères.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-2">
            <div className="space-y-1.5">
              <Label htmlFor="cp-current">Mot de passe actuel</Label>
              <Input
                id="cp-current"
                type="password"
                value={currentPassword}
                onChange={(e) => setCurrentPassword(e.target.value)}
                placeholder="••••••••"
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="cp-new">Nouveau mot de passe</Label>
              <Input
                id="cp-new"
                type="password"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                placeholder="••••••••"
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="cp-confirm">Confirmer le mot de passe</Label>
              <Input
                id="cp-confirm"
                type="password"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                placeholder="••••••••"
              />
              {confirmPassword && newPassword !== confirmPassword && (
                <p className="text-xs text-destructive">Les mots de passe ne correspondent pas</p>
              )}
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowPasswordModal(false)}>Annuler</Button>
            <Button
              onClick={handleChangePassword}
              disabled={isLoading || !currentPassword || !newPassword || newPassword !== confirmPassword}
              className="gap-1.5"
            >
              {isLoading && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
              Modifier le mot de passe
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

// ─── Onglet Taxes ──────────────────────────────────────────────

type TaxRate = {
  id: string;
  name: string;
  rate: number;
  isDefault: boolean;
  isActive: boolean;
};

function TaxesTab() {
  const [taxes, setTaxes] = useState<TaxRate[]>([]);
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<TaxRate | null>(null);
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);

  const [form, setForm] = useState({ name: "", rate: "", isDefault: false });

  const fetchTaxes = () => {
    setLoading(true);
    fetch("/api/tax-rates")
      .then((r) => r.json())
      .then((j) => { if (j.success) setTaxes(j.data); })
      .catch(() => {})
      .finally(() => setLoading(false));
  };

  useEffect(() => { fetchTaxes(); }, []);

  function openCreate() {
    setEditing(null);
    setForm({ name: "", rate: "", isDefault: false });
    setDialogOpen(true);
  }

  function openEdit(tax: TaxRate) {
    setEditing(tax);
    setForm({ name: tax.name, rate: String(tax.rate), isDefault: tax.isDefault });
    setDialogOpen(true);
  }

  async function handleSave() {
    if (!form.name.trim() || form.rate === "") return;
    setSaving(true);
    try {
      const body = { name: form.name.trim(), rate: parseFloat(form.rate), isDefault: form.isDefault };
      const url = editing ? `/api/tax-rates/${editing.id}` : "/api/tax-rates";
      const method = editing ? "PATCH" : "POST";
      const r = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
      const j = await r.json();
      if (!j.success) { toast.error(j.error ?? "Erreur"); return; }
      toast.success(editing ? "Taux mis à jour" : "Taux créé");
      setDialogOpen(false);
      fetchTaxes();
    } catch {
      toast.error("Erreur réseau");
    } finally {
      setSaving(false);
    }
  }

  async function toggleActive(tax: TaxRate) {
    const r = await fetch(`/api/tax-rates/${tax.id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ isActive: !tax.isActive }),
    });
    const j = await r.json();
    if (j.success) fetchTaxes();
    else toast.error(j.error ?? "Erreur");
  }

  async function handleDelete() {
    if (!deleteId) return;
    const r = await fetch(`/api/tax-rates/${deleteId}`, { method: "DELETE" });
    const j = await r.json();
    if (j.success) { toast.success("Taux supprimé"); fetchTaxes(); }
    else toast.error(j.error ?? "Erreur");
    setDeleteId(null);
  }

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader className="flex flex-row items-center justify-between pb-4">
          <div>
            <CardTitle className="text-base flex items-center gap-2">
              <Percent className="h-4 w-4 text-primary" />
              Taux de taxe / TVA
            </CardTitle>
            <CardDescription className="text-sm mt-1">
              Gérez les taux applicables sur vos factures et devis. Le taux par défaut est pré-sélectionné sur les nouvelles lignes.
            </CardDescription>
          </div>
          <Button size="sm" className="gap-1.5 shrink-0" onClick={openCreate}>
            <Plus className="h-3.5 w-3.5" />
            Ajouter un taux
          </Button>
        </CardHeader>
        <CardContent className="p-0">
          {loading ? (
            <div className="flex items-center justify-center py-10">
              <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
            </div>
          ) : taxes.length === 0 ? (
            <div className="flex flex-col items-center py-10 gap-2 text-muted-foreground">
              <Percent className="h-8 w-8 opacity-30" />
              <p className="text-sm">Aucun taux configuré</p>
              <Button variant="outline" size="sm" onClick={openCreate}>Créer le premier taux</Button>
            </div>
          ) : (
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b text-xs text-muted-foreground">
                  <th className="text-left font-medium px-6 py-3">Nom</th>
                  <th className="text-center font-medium px-3 py-3">Taux</th>
                  <th className="text-center font-medium px-3 py-3">Défaut</th>
                  <th className="text-center font-medium px-3 py-3">Actif</th>
                  <th className="px-6 py-3" />
                </tr>
              </thead>
              <tbody>
                {taxes.map((tax) => (
                  <tr key={tax.id} className="border-b last:border-0 hover:bg-muted/30 transition-colors">
                    <td className="px-6 py-3">
                      <div className="flex items-center gap-2">
                        <span className="font-medium">{tax.name}</span>
                        {tax.isDefault && (
                          <span className="inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400">
                            <Star className="h-2.5 w-2.5" />
                            Défaut
                          </span>
                        )}
                      </div>
                    </td>
                    <td className="px-3 py-3 text-center">
                      <span className="font-mono font-semibold tabular-nums">{Number(tax.rate)}%</span>
                    </td>
                    <td className="px-3 py-3 text-center">
                      <Switch
                        checked={tax.isDefault}
                        onCheckedChange={async () => {
                          const r = await fetch(`/api/tax-rates/${tax.id}`, {
                            method: "PATCH",
                            headers: { "Content-Type": "application/json" },
                            body: JSON.stringify({ isDefault: true }),
                          });
                          const j = await r.json();
                          if (j.success) fetchTaxes();
                        }}
                      />
                    </td>
                    <td className="px-3 py-3 text-center">
                      <Switch checked={tax.isActive} onCheckedChange={() => toggleActive(tax)} />
                    </td>
                    <td className="px-6 py-3">
                      <div className="flex items-center justify-end gap-1">
                        <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => openEdit(tax)}>
                          <Pencil className="h-3.5 w-3.5" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-7 w-7 text-muted-foreground hover:text-destructive"
                          onClick={() => setDeleteId(tax.id)}
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </CardContent>
      </Card>

      {/* Dialog création / édition */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="sm:max-w-sm">
          <DialogHeader>
            <DialogTitle>{editing ? "Modifier le taux" : "Nouveau taux de taxe"}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-2">
            <div className="space-y-1.5">
              <Label>Nom</Label>
              <Input
                placeholder="Ex : TVA 20%, Exonéré, IS 30%…"
                value={form.name}
                onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
              />
            </div>
            <div className="space-y-1.5">
              <Label>Taux (%)</Label>
              <Input
                type="number"
                min="0"
                max="100"
                step="0.01"
                placeholder="Ex : 20"
                value={form.rate}
                onChange={(e) => setForm((f) => ({ ...f, rate: e.target.value }))}
              />
            </div>
            <div className="flex items-center justify-between rounded-lg border p-3">
              <div>
                <p className="text-sm font-medium">Taux par défaut</p>
                <p className="text-xs text-muted-foreground">Pré-sélectionné sur les nouvelles lignes de facture</p>
              </div>
              <Switch
                checked={form.isDefault}
                onCheckedChange={(v) => setForm((f) => ({ ...f, isDefault: v }))}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDialogOpen(false)}>Annuler</Button>
            <Button onClick={handleSave} disabled={saving || !form.name.trim() || form.rate === ""} className="gap-1.5">
              {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
              {editing ? "Enregistrer" : "Créer"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Confirmation suppression */}
      <AlertDialog open={!!deleteId} onOpenChange={(o) => !o && setDeleteId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Supprimer ce taux ?</AlertDialogTitle>
            <AlertDialogDescription>
              Cette action est irréversible. Les factures existantes ne sont pas affectées.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Annuler</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete} className="bg-destructive hover:bg-destructive/90">
              Supprimer
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}

// ─── Composant principal ───────────────────────────────────────

export default function ParametresPage() {
  const { data: session } = useSession();
  const [org, setOrg] = useState<OrgData | null>(null);
  const [isLoadingOrg, setIsLoadingOrg] = useState(true);

  const fetchOrg = () => {
    if (!session?.user) return;
    setIsLoadingOrg(true);
    fetch("/api/organizations/current")
      .then((r) => r.json())
      .then((data) => {
        if (data.success) setOrg(data.data);
      })
      .catch(() => {})
      .finally(() => setIsLoadingOrg(false));
  };

  useEffect(() => {
    fetchOrg();
  }, [session?.user]);

  return (
    <div className="space-y-6">
      {/* En-tête */}
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Paramètres</h1>
        <p className="text-sm text-muted-foreground mt-0.5">
          Gérez votre profil, votre organisation et vos préférences
        </p>
      </div>

      {/* Onglets */}
      <Tabs defaultValue="profile" className="space-y-6">
        <TabsList className="h-10 gap-1">
          <TabsTrigger value="profile" className="gap-1.5 text-sm">
            <User className="h-3.5 w-3.5" />
            Profil utilisateur
          </TabsTrigger>
          <TabsTrigger value="organization" className="gap-1.5 text-sm">
            <Building2 className="h-3.5 w-3.5" />
            Organisation
          </TabsTrigger>
          <TabsTrigger value="members" className="gap-1.5 text-sm">
            <Users className="h-3.5 w-3.5" />
            Membres
          </TabsTrigger>
          <TabsTrigger value="taxes" className="gap-1.5 text-sm">
            <Percent className="h-3.5 w-3.5" />
            Taxes
          </TabsTrigger>
          <TabsTrigger value="security" className="gap-1.5 text-sm">
            <Shield className="h-3.5 w-3.5" />
            Sécurité
          </TabsTrigger>
        </TabsList>

        <TabsContent value="profile" className="mt-0">
          {session ? (
            <ProfileTab session={session} />
          ) : (
            <div className="flex items-center gap-2 text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin" />
              <span className="text-sm">Chargement…</span>
            </div>
          )}
        </TabsContent>

        <TabsContent value="organization" className="mt-0">
          {isLoadingOrg ? (
            <div className="flex items-center gap-2 text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin" />
              <span className="text-sm">Chargement…</span>
            </div>
          ) : (
            <OrganizationTab org={org} onRefresh={fetchOrg} />
          )}
        </TabsContent>

        <TabsContent value="members" className="mt-0">
          {isLoadingOrg ? (
            <div className="flex items-center gap-2 text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin" />
              <span className="text-sm">Chargement…</span>
            </div>
          ) : (
            <MembersTab members={org?.members ?? []} onRefresh={fetchOrg} />
          )}
        </TabsContent>

        <TabsContent value="taxes" className="mt-0">
          <TaxesTab />
        </TabsContent>

        <TabsContent value="security" className="mt-0">
          <SecurityTab />
        </TabsContent>
      </Tabs>
    </div>
  );
}
