import { useState, useEffect, useMemo } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ShieldCheck, Save, Loader2 } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";

const ROLE_LABELS: Record<string, { label: string; color: string }> = {
  homeowner: { label: "Homeowner", color: "bg-blue-100 text-blue-700" },
  rv_boat_lot: { label: "RV/Boat Lot", color: "bg-cyan-100 text-cyan-700" },
  board_member: { label: "Board Member", color: "bg-purple-100 text-purple-700" },
  arc_member: { label: "ARC Member", color: "bg-amber-100 text-amber-700" },
  fining_member: { label: "Fining Member", color: "bg-rose-100 text-rose-700" },
  management: { label: "Management", color: "bg-emerald-100 text-emerald-700" },
  association_management: { label: "Association Management (Commercial)", color: "bg-teal-100 text-teal-700" },
};

const ROLES = Object.keys(ROLE_LABELS);

const FEATURE_GROUPS: { group: string; features: string[] }[] = [
  { group: "Community", features: ["Announcements", "Calendar", "Documents", "Parking"] },
  { group: "Owner Services", features: ["Owner Portal", "Violations", "Collections", "Estoppels"] },
  { group: "Reviews & Governance", features: ["ARC Applications", "Board Votes", "Inspections", "Legal Matters"] },
  { group: "Financial", features: ["Financial", "Owners & Units", "Vendors & Bills", "Projects"] },
  { group: "Communications", features: ["Email & Notifications"] },
];

const ACTIONS = ["can_read", "can_create", "can_edit", "can_delete"] as const;
const ACTION_LABELS: Record<string, string> = {
  can_read: "Read",
  can_create: "Create",
  can_edit: "Edit",
  can_delete: "Delete",
};

type PermRow = {
  id: string;
  role: string;
  feature_area: string;
  can_read: boolean;
  can_create: boolean;
  can_edit: boolean;
  can_delete: boolean;
};

export default function RolePermissionsPage() {
  const { toast } = useToast();
  const [permissions, setPermissions] = useState<PermRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [dirty, setDirty] = useState(false);
  const [activeRole, setActiveRole] = useState(ROLES[0]);

  const fetchPermissions = async () => {
    setLoading(true);
    const { data, error } = await supabase
      .from("role_permissions")
      .select("*")
      .in("role", ROLES)
      .order("feature_area");
    if (error) toast({ variant: "destructive", title: "Error loading permissions", description: error.message });
    else setPermissions((data as PermRow[]) || []);
    setLoading(false);
    setDirty(false);
  };

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

  const permMap = useMemo(() => {
    const map = new Map<string, PermRow>();
    permissions.forEach(p => map.set(`${p.role}::${p.feature_area}`, p));
    return map;
  }, [permissions]);

  const toggle = (role: string, feature: string, action: typeof ACTIONS[number]) => {
    setPermissions(prev => prev.map(p => {
      if (p.role === role && p.feature_area === feature) {
        return { ...p, [action]: !p[action] };
      }
      return p;
    }));
    setDirty(true);
  };

  const toggleAll = (role: string, feature: string, value: boolean) => {
    setPermissions(prev => prev.map(p => {
      if (p.role === role && p.feature_area === feature) {
        return { ...p, can_read: value, can_create: value, can_edit: value, can_delete: value };
      }
      return p;
    }));
    setDirty(true);
  };

  const handleSave = async () => {
    setSaving(true);
    const rolePerms = permissions.filter(p => ROLES.includes(p.role));
    
    // Batch upsert
    const promises = rolePerms.map(p =>
      supabase.from("role_permissions").update({
        can_read: p.can_read,
        can_create: p.can_create,
        can_edit: p.can_edit,
        can_delete: p.can_delete,
      }).eq("id", p.id)
    );
    
    const results = await Promise.all(promises);
    const hasError = results.some(r => r.error);
    
    if (hasError) {
      toast({ variant: "destructive", title: "Error saving some permissions" });
    } else {
      toast({ title: "Permissions saved successfully" });
      setDirty(false);
    }
    setSaving(false);
  };

  const roleInfo = ROLE_LABELS[activeRole];

  return (
    <div className="space-y-6">
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2">
            <ShieldCheck className="h-6 w-6 text-primary" />
            Role Permissions
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            Configure read, create, edit, and delete access per feature area for each portal role.
          </p>
        </div>
        <Button onClick={handleSave} disabled={!dirty || saving} className="gap-2">
          {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
          Save Changes
        </Button>
      </div>

      {loading ? (
        <div className="flex justify-center py-16">
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
        </div>
      ) : (
        <Tabs value={activeRole} onValueChange={setActiveRole}>
          <TabsList className="flex flex-wrap h-auto gap-1">
            {ROLES.map(role => (
              <TabsTrigger key={role} value={role} className="gap-1.5 text-xs">
                {ROLE_LABELS[role].label}
              </TabsTrigger>
            ))}
          </TabsList>

          {ROLES.map(role => (
            <TabsContent key={role} value={role} className="space-y-4 mt-4">
              <div className="flex items-center gap-2 mb-2">
                <Badge className={`${ROLE_LABELS[role].color} border-0`}>
                  {ROLE_LABELS[role].label}
                </Badge>
                <span className="text-sm text-muted-foreground">— Feature permissions</span>
              </div>

              {FEATURE_GROUPS.map(group => {
                const features = group.features;
                return (
                  <Card key={group.group}>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-semibold">{group.group}</CardTitle>
                    </CardHeader>
                    <CardContent className="p-0">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead className="w-[200px]">Feature Area</TableHead>
                            {ACTIONS.map(a => (
                              <TableHead key={a} className="text-center w-[90px]">{ACTION_LABELS[a]}</TableHead>
                            ))}
                            <TableHead className="text-center w-[90px]">All</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {features.map(feature => {
                            const perm = permMap.get(`${role}::${feature}`);
                            if (!perm) return null;
                            const allChecked = ACTIONS.every(a => perm[a]);
                            const noneChecked = ACTIONS.every(a => !perm[a]);

                            return (
                              <TableRow key={feature}>
                                <TableCell className="font-medium text-sm">{feature}</TableCell>
                                {ACTIONS.map(action => (
                                  <TableCell key={action} className="text-center">
                                    <Checkbox
                                      checked={perm[action]}
                                      onCheckedChange={() => toggle(role, feature, action)}
                                    />
                                  </TableCell>
                                ))}
                                <TableCell className="text-center">
                                  <Checkbox
                                    checked={allChecked}
                                    onCheckedChange={() => toggleAll(role, feature, !allChecked)}
                                  />
                                </TableCell>
                              </TableRow>
                            );
                          })}
                        </TableBody>
                      </Table>
                    </CardContent>
                  </Card>
                );
              })}
            </TabsContent>
          ))}
        </Tabs>
      )}
    </div>
  );
}
