import { useState } from 'react';
import { useParams, Link } from 'react-router';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Plus, Network, Wifi, WifiOff } from 'lucide-react';
import { api } from '@/lib/api';
import { formatBytes } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';

interface NodeItem {
  id: string;
  name: string;
  fqdn: string;
  daemonPort: number;
  grpcPort: number;
  memoryTotal: number;
  diskTotal: number;
  isOnline: boolean;
}

interface PaginatedResponse<T> {
  data: T[];
  meta: { total: number };
}

export function NodesPage() {
  const { orgId } = useParams();
  const queryClient = useQueryClient();
  const [open, setOpen] = useState(false);
  const [name, setName] = useState('');
  const [fqdn, setFqdn] = useState('');
  const [daemonPort, setDaemonPort] = useState(8443);
  const [grpcPort, setGrpcPort] = useState(50051);
  const [memoryTotal, setMemoryTotal] = useState(8192);
  const [diskTotal, setDiskTotal] = useState(51200);

  const { data } = useQuery({
    queryKey: ['nodes', orgId],
    queryFn: () => api.get<PaginatedResponse<NodeItem>>(`/organizations/${orgId}/nodes`),
  });

  const createMutation = useMutation({
    mutationFn: (body: Record<string, unknown>) =>
      api.post(`/organizations/${orgId}/nodes`, body),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['nodes', orgId] });
      setOpen(false);
      setName('');
      setFqdn('');
    },
  });

  const nodes = data?.data ?? [];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Nodes</h1>
          <p className="text-muted-foreground">Manage your daemon nodes</p>
        </div>
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="h-4 w-4" /> Add Node
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Add Node</DialogTitle>
            </DialogHeader>
            <form
              onSubmit={(e) => {
                e.preventDefault();
                createMutation.mutate({
                  name,
                  fqdn,
                  daemonPort,
                  grpcPort,
                  memoryTotal: memoryTotal * 1024 * 1024,
                  diskTotal: diskTotal * 1024 * 1024,
                });
              }}
              className="space-y-4"
            >
              <div className="grid gap-4 sm:grid-cols-2">
                <div className="space-y-2">
                  <Label>Name</Label>
                  <Input value={name} onChange={(e) => setName(e.target.value)} required />
                </div>
                <div className="space-y-2">
                  <Label>FQDN</Label>
                  <Input
                    value={fqdn}
                    onChange={(e) => setFqdn(e.target.value)}
                    placeholder="node1.example.com"
                    required
                  />
                </div>
                <div className="space-y-2">
                  <Label>Daemon Port</Label>
                  <Input
                    type="number"
                    value={daemonPort}
                    onChange={(e) => setDaemonPort(Number(e.target.value))}
                  />
                </div>
                <div className="space-y-2">
                  <Label>gRPC Port</Label>
                  <Input
                    type="number"
                    value={grpcPort}
                    onChange={(e) => setGrpcPort(Number(e.target.value))}
                  />
                </div>
                <div className="space-y-2">
                  <Label>Memory (MB)</Label>
                  <Input
                    type="number"
                    value={memoryTotal}
                    onChange={(e) => setMemoryTotal(Number(e.target.value))}
                  />
                </div>
                <div className="space-y-2">
                  <Label>Disk (MB)</Label>
                  <Input
                    type="number"
                    value={diskTotal}
                    onChange={(e) => setDiskTotal(Number(e.target.value))}
                  />
                </div>
              </div>
              <DialogFooter>
                <Button type="submit" disabled={createMutation.isPending}>
                  {createMutation.isPending ? 'Creating...' : 'Add Node'}
                </Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>
      </div>

      <div className="grid gap-4 sm:grid-cols-2">
        {nodes.map((node) => (
          <Link key={node.id} to={`/org/${orgId}/nodes/${node.id}`}>
          <Card className="transition-colors hover:bg-muted/50 cursor-pointer">
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <div className="flex items-center gap-3">
                <Network className="h-5 w-5 text-primary" />
                <CardTitle className="text-base">{node.name}</CardTitle>
              </div>
              <Badge variant={node.isOnline ? 'default' : 'destructive'}>
                {node.isOnline ? (
                  <><Wifi className="mr-1 h-3 w-3" /> Online</>
                ) : (
                  <><WifiOff className="mr-1 h-3 w-3" /> Offline</>
                )}
              </Badge>
            </CardHeader>
            <CardContent>
              <p className="text-sm text-muted-foreground">{node.fqdn}:{node.daemonPort}</p>
              <div className="mt-3 flex gap-4 text-sm">
                <span>{formatBytes(node.memoryTotal)} RAM</span>
                <span>{formatBytes(node.diskTotal)} Disk</span>
              </div>
            </CardContent>
          </Card>
          </Link>
        ))}
      </div>
    </div>
  );
}
