'use client';

import { createProxyFetch } from '@/lib/proxy-fetch';

import { useState, useEffect, useCallback } from 'react';
import { Building2, Plus, MoreHorizontal, Users, FolderOpen, Search, Trash2 } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from '@/components/ui/sheet';

interface Org {
  id: string;
  name: string;
  slug: string;
  status: string;
  memberCount?: number;
  workspaceCount?: number;
  createdAt: string;
}

interface Member {
  id: string;
  userId: string;
  role: string;
  email?: string;
  name?: string;
  createdAt: string;
}

interface Workspace {
  id: string;
  name: string;
  slug: string;
  createdAt: string;
}

function formatDate(iso: string) {
  return new Date(iso).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  });
}

const apiFetch = createProxyFetch('/api/orgs');

export default function OrganizationsPage() {
  const [orgs, setOrgs] = useState<Org[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [showCreate, setShowCreate] = useState(false);
  const [newName, setNewName] = useState('');
  const [newSlug, setNewSlug] = useState('');
  const [creating, setCreating] = useState(false);

  // Detail drawer
  const [selectedOrg, setSelectedOrg] = useState<Org | null>(null);
  const [members, setMembers] = useState<Member[]>([]);
  const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
  const [detailLoading, setDetailLoading] = useState(false);

  const loadOrgs = useCallback(async () => {
    setLoading(true);
    const qs = search ? `?search=${encodeURIComponent(search)}` : '';
    const data = await apiFetch(qs);
    if (data?.organizations) {
      setOrgs(data.organizations);
      setTotal(data.total ?? data.organizations.length);
    } else if (Array.isArray(data)) {
      setOrgs(data);
      setTotal(data.length);
    }
    setLoading(false);
  }, [search]);

  useEffect(() => {
    void loadOrgs();
  }, [loadOrgs]);

  async function handleCreate() {
    setCreating(true);
    await apiFetch('', {
      method: 'POST',
      body: JSON.stringify({ name: newName, slug: newSlug || undefined }),
    });
    setCreating(false);
    setShowCreate(false);
    setNewName('');
    setNewSlug('');
    loadOrgs();
  }

  async function handleDelete(id: string) {
    if (!confirm('Delete this organization? This cannot be undone.')) return;
    await apiFetch(`${id}`, { method: 'DELETE' });
    loadOrgs();
    if (selectedOrg?.id === id) setSelectedOrg(null);
  }

  async function openDetail(org: Org) {
    setSelectedOrg(org);
    setDetailLoading(true);
    const [membersData, wsData] = await Promise.all([
      apiFetch(`${org.id}/memberships`),
      apiFetch(`${org.id}/workspaces`),
    ]);
    setMembers(
      Array.isArray(membersData?.memberships)
        ? membersData.memberships
        : Array.isArray(membersData)
          ? membersData
          : []
    );
    setWorkspaces(
      Array.isArray(wsData?.workspaces) ? wsData.workspaces : Array.isArray(wsData) ? wsData : []
    );
    setDetailLoading(false);
  }

  const activeOrgs = orgs.filter(o => o.status === 'active');

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Organizations</h1>
          <p className="text-sm text-muted-foreground">
            Manage organizations, workspaces, and memberships
          </p>
        </div>
        <Button onClick={() => setShowCreate(true)}>
          <Plus className="mr-2 h-4 w-4" /> Create Organization
        </Button>
      </div>

      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total Organizations
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{total}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Active</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{activeOrgs.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total Members
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {orgs.reduce((sum, o) => sum + (o.memberCount ?? 0), 0)}
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="flex items-center gap-4">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Search organizations..."
            value={search}
            onChange={e => setSearch(e.target.value)}
            className="pl-9"
          />
        </div>
      </div>

      <Card>
        <CardContent className="p-0">
          {loading ? (
            <div className="p-8 text-center text-muted-foreground">Loading...</div>
          ) : orgs.length === 0 ? (
            <div className="p-8 text-center text-muted-foreground">
              <Building2 className="mx-auto mb-2 h-8 w-8 opacity-40" />
              No organizations yet. Create one to get started.
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Organization</TableHead>
                  <TableHead>Slug</TableHead>
                  <TableHead>Members</TableHead>
                  <TableHead>Workspaces</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Created</TableHead>
                  <TableHead className="w-[50px]" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {orgs.map(org => (
                  <TableRow key={org.id} className="cursor-pointer" onClick={() => openDetail(org)}>
                    <TableCell className="font-medium">{org.name}</TableCell>
                    <TableCell>
                      <code className="text-xs text-muted-foreground">{org.slug}</code>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1">
                        <Users className="h-3.5 w-3.5 text-muted-foreground" />
                        {org.memberCount ?? 0}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1">
                        <FolderOpen className="h-3.5 w-3.5 text-muted-foreground" />
                        {org.workspaceCount ?? 0}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge
                        variant="outline"
                        className={
                          org.status === 'active'
                            ? 'bg-emerald-50 text-emerald-700 border-0'
                            : 'bg-gray-50 text-gray-600 border-0'
                        }
                      >
                        {org.status}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-muted-foreground text-xs">
                      {formatDate(org.createdAt)}
                    </TableCell>
                    <TableCell onClick={e => e.stopPropagation()}>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon" className="h-8 w-8">
                            <MoreHorizontal className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem onClick={() => openDetail(org)}>
                            View Details
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            onClick={() => handleDelete(org.id)}
                            className="text-destructive"
                          >
                            <Trash2 className="mr-2 h-4 w-4" /> Delete
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* Create Dialog */}
      <Dialog open={showCreate} onOpenChange={setShowCreate}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Create Organization</DialogTitle>
            <DialogDescription>
              Create a new organization with workspaces and members.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Name</Label>
              <Input
                placeholder="e.g. Acme Corp"
                value={newName}
                onChange={e => setNewName(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label>Slug (optional — auto-generated)</Label>
              <Input
                placeholder="e.g. acme-corp"
                value={newSlug}
                onChange={e => setNewSlug(e.target.value)}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowCreate(false)}>
              Cancel
            </Button>
            <Button onClick={handleCreate} disabled={creating || !newName.trim()}>
              {creating ? 'Creating...' : 'Create'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Detail Sheet */}
      <Sheet open={!!selectedOrg} onOpenChange={open => !open && setSelectedOrg(null)}>
        <SheetContent className="w-[480px] sm:w-[540px] overflow-auto">
          <SheetHeader>
            <SheetTitle>{selectedOrg?.name}</SheetTitle>
            <SheetDescription>
              <code className="text-xs">{selectedOrg?.id}</code>
            </SheetDescription>
          </SheetHeader>
          {detailLoading ? (
            <div className="py-12 text-center text-muted-foreground">Loading...</div>
          ) : (
            <div className="space-y-6 mt-6">
              <div>
                <h3 className="text-sm font-semibold mb-3 flex items-center gap-2">
                  <Users className="h-4 w-4" /> Members ({members.length})
                </h3>
                {members.length === 0 ? (
                  <p className="text-sm text-muted-foreground">No members yet.</p>
                ) : (
                  <div className="space-y-2">
                    {members.map(m => (
                      <div
                        key={m.id}
                        className="flex items-center justify-between rounded-lg border p-3"
                      >
                        <div>
                          <p className="text-sm font-medium">{m.name || m.email || m.userId}</p>
                          <p className="text-xs text-muted-foreground">{m.email}</p>
                        </div>
                        <Badge variant="outline" className="capitalize">
                          {m.role}
                        </Badge>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              <div>
                <h3 className="text-sm font-semibold mb-3 flex items-center gap-2">
                  <FolderOpen className="h-4 w-4" /> Workspaces ({workspaces.length})
                </h3>
                {workspaces.length === 0 ? (
                  <p className="text-sm text-muted-foreground">No workspaces yet.</p>
                ) : (
                  <div className="space-y-2">
                    {workspaces.map(ws => (
                      <div
                        key={ws.id}
                        className="flex items-center justify-between rounded-lg border p-3"
                      >
                        <div>
                          <p className="text-sm font-medium">{ws.name}</p>
                          <code className="text-xs text-muted-foreground">{ws.slug}</code>
                        </div>
                        <span className="text-xs text-muted-foreground">
                          {formatDate(ws.createdAt)}
                        </span>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          )}
        </SheetContent>
      </Sheet>
    </div>
  );
}
