import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Card, CardContent } from './ui/card';
import { Button } from './ui/button';
import { Input, Label } from './ui';
import { Alert, AlertDescription } from './ui/alert';
import { Textarea } from './ui/textarea';
import { Badge } from './ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from './ui/collapsible';
import {
  Globe, Loader2, AlertCircle, CheckCircle, Play, RotateCw,
  Plus, Trash2, X, ChevronDown, ChevronRight, ChevronUp,
} from 'lucide-react';
import { useConfig } from '../hooks';
import { useHaproxy } from '../hooks/useHaproxy';
import { useServices } from '../hooks/useServices';
import { useCert } from '../hooks/useCert';
import { useDdns } from '../hooks/useDdns';
import { usePageHelp } from '../hooks/usePageHelp';
import type { RegisteredService } from '../services/api/networking';
import { servicesApi, haproxyApi } from '../services/api/networking';

function StatusDot({ status, label }: { status: 'ok' | 'error' | 'na'; label: string }) {
  return (
    <span className="inline-flex items-center gap-1 text-xs">
      {status === 'ok' && <CheckCircle className="h-3.5 w-3.5 text-green-500" />}
      {status === 'error' && <AlertCircle className="h-3.5 w-3.5 text-red-500" />}
      {status === 'na' && <CheckCircle className="h-3.5 w-3.5 text-muted-foreground" />}
      <span className="text-muted-foreground">{label}</span>
    </span>
  );
}

function getTlsStatus(service: RegisteredService, certDomains: Set<string>): 'ok' | 'error' | 'na' {
  // Passthrough: Central doesn't handle TLS — grey (not applicable)
  if (service.tls === 'passthrough' || service.backend.type === 'tcp-passthrough') return 'na';
  // Terminate: Central handles TLS — green if cert exists, red if missing
  return certDomains.has(service.domain) ? 'ok' : 'error';
}

function getProxyLabel(service: RegisteredService): string {
  if (service.backend.type === 'tcp-passthrough') {
    return `L4 SNI passthrough${service.subdomains ? ' + wildcard' : ''}`;
  }
  return `L7 HTTP reverse proxy`;
}

function getTlsLabel(service: RegisteredService, certDomains: Set<string>): string {
  if (service.tls === 'passthrough' || service.backend.type === 'tcp-passthrough') return 'passthrough (backend handles)';
  return certDomains.has(service.domain) ? 'terminate (cert provisioned)' : 'terminate (cert missing)';
}

export function ServicesComponent() {
  const queryClient = useQueryClient();
  const { config: globalConfig } = useConfig();
  const {
    generate: generateHaproxy, isGenerating: isHaproxyGenerating,
    generateData: haproxyGenerateData, generateError: haproxyGenerateError,
    restart: restartHaproxy, isRestarting: isHaproxyRestarting,
  } = useHaproxy();
  const { services, isLoading: isServicesLoading } = useServices();
  const { status: certStatus } = useCert();
  const { status: ddnsStatus } = useDdns();

  const [expandedDomain, setExpandedDomain] = useState<string | null>(null);
  const [showAddForm, setShowAddForm] = useState(false);
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [advancedConfig, setAdvancedConfig] = useState('');
  const [loadingAdvanced, setLoadingAdvanced] = useState(false);

  // Add service form state
  const [newDomain, setNewDomain] = useState('');
  const [newBackendAddr, setNewBackendAddr] = useState('');
  const [newBackendType, setNewBackendType] = useState<string>('tcp-passthrough');
  const [newReach, setNewReach] = useState<string>('public');
  const [newSubdomains, setNewSubdomains] = useState(false);

  const certDomains = new Set<string>(
    (certStatus?.certs ?? []).filter(c => c.cert.exists).map(c => c.domain)
  );
  const publicIp = ddnsStatus?.currentIP;

  const registerMutation = useMutation({
    mutationFn: (svc: { domain: string; backend: { address: string; type: string }; reach: string; subdomains: boolean; source: string }) =>
      servicesApi.register(svc),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['services'] });
      setShowAddForm(false);
      setNewDomain(''); setNewBackendAddr(''); setNewBackendType('tcp-passthrough'); setNewReach('public'); setNewSubdomains(false);
    },
  });

  const deregisterMutation = useMutation({
    mutationFn: (domain: string) => servicesApi.deregister(domain),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['services'] }),
  });

  usePageHelp({
    title: 'Services',
    description: (
      <p className="leading-relaxed">
        Each service represents a domain that Wild Central manages. When a service is registered,
        Central creates DNS entries, proxy routes, and optionally provisions TLS certificates
        and public DNS records.
      </p>
    ),
  });

  const handleShowAdvanced = async () => {
    if (!showAdvanced) {
      setLoadingAdvanced(true);
      try {
        const result = await haproxyApi.getConfig();
        setAdvancedConfig(result.content || '');
      } catch {
        setAdvancedConfig('# Could not load HAProxy config');
      }
      setLoadingAdvanced(false);
    }
    setShowAdvanced(!showAdvanced);
  };

  return (
    <div className="space-y-4">
      {/* Page header */}
      <div className="flex items-center justify-between mb-2">
        <div className="flex items-center gap-4">
          <div className="p-2 bg-primary/10 rounded-lg">
            <Globe className="h-6 w-6 text-primary" />
          </div>
          <div>
            <h2 className="text-2xl font-semibold">Services</h2>
            <p className="text-muted-foreground">Registered domains and their networking status</p>
          </div>
        </div>
        <Button onClick={() => setShowAddForm(!showAddForm)} className="gap-1">
          <Plus className="h-4 w-4" />
          Add Service
        </Button>
      </div>

      {/* Add Service Form */}
      {showAddForm && (
        <Card className="border-dashed border-primary/50">
          <CardContent className="p-4 space-y-3">
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label className="text-xs">Domain</Label>
                <Input value={newDomain} onChange={e => setNewDomain(e.target.value)} placeholder="cloud.payne.io" className="mt-1 font-mono" />
              </div>
              <div>
                <Label className="text-xs">Backend (host:port)</Label>
                <Input value={newBackendAddr} onChange={e => setNewBackendAddr(e.target.value)} placeholder="192.168.8.240:443" className="mt-1 font-mono" />
              </div>
              <div>
                <Label className="text-xs">Type</Label>
                <Select value={newBackendType} onValueChange={setNewBackendType}>
                  <SelectTrigger className="mt-1"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="tcp-passthrough">L4 TCP Passthrough</SelectItem>
                    <SelectItem value="http">L7 HTTP Reverse Proxy</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label className="text-xs">Reach</Label>
                <Select value={newReach} onValueChange={setNewReach}>
                  <SelectTrigger className="mt-1"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="public">Public (LAN + Internet)</SelectItem>
                    <SelectItem value="internal">Internal (LAN only)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <label className="flex items-center gap-2 text-sm">
              <input type="checkbox" checked={newSubdomains} onChange={e => setNewSubdomains(e.target.checked)} className="rounded" />
              Include wildcard subdomains (*.domain)
            </label>
            <div className="flex gap-2 justify-end">
              <Button variant="outline" size="sm" onClick={() => setShowAddForm(false)}><X className="h-3 w-3 mr-1" />Cancel</Button>
              <Button
                size="sm"
                disabled={!newDomain || !newBackendAddr || registerMutation.isPending}
                onClick={() => registerMutation.mutate({
                  domain: newDomain,
                  backend: { address: newBackendAddr, type: newBackendType },
                  reach: newReach,
                  subdomains: newSubdomains,
                  source: 'manual',
                })}
              >
                {registerMutation.isPending ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : <Plus className="h-3 w-3 mr-1" />}
                Register
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Loading */}
      {isServicesLoading && (
        <Card className="p-8 text-center">
          <Loader2 className="h-8 w-8 text-primary mx-auto mb-2 animate-spin" />
          <p className="text-sm text-muted-foreground">Loading services...</p>
        </Card>
      )}

      {/* Empty state */}
      {!isServicesLoading && services.length === 0 && (
        <Card className="p-8 text-center">
          <Globe className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
          <h3 className="text-lg font-medium mb-2">No Services</h3>
          <p className="text-muted-foreground mb-4">
            Services appear here when Wild Cloud or Wild Works registers domains,
            or add one manually.
          </p>
        </Card>
      )}

      {/* Service Cards */}
      {services.map(service => {
        const isExpanded = expandedDomain === service.domain;
        const tlsStatus = getTlsStatus(service, certDomains);
        const ddnsStatus2 = service.reach === 'public' ? 'ok' as const : 'na' as const;

        return (
          <Card key={service.domain} className="overflow-hidden">
            <button
              type="button"
              onClick={() => setExpandedDomain(isExpanded ? null : service.domain)}
              className="w-full px-4 py-3 text-left hover:bg-muted/30 transition-colors"
            >
              <div className="flex items-center justify-between gap-2">
                <div className="flex items-center gap-2 min-w-0">
                  {isExpanded ? <ChevronDown className="h-4 w-4 text-muted-foreground shrink-0" />
                    : <ChevronRight className="h-4 w-4 text-muted-foreground shrink-0" />}
                  <span className="font-mono text-sm font-medium truncate">
                    {service.subdomains ? `*.${service.domain}` : service.domain}
                  </span>
                  <Badge variant="outline" className="text-xs h-5 shrink-0">
                    {service.backend.type === 'tcp-passthrough' ? 'L4' : 'L7'}
                  </Badge>
                  <Badge variant={service.reach === 'public' ? 'success' : 'default'} className="text-xs h-5 shrink-0">
                    {service.reach}
                  </Badge>
                </div>
                <div className="flex items-center gap-3 shrink-0">
                  <StatusDot status="ok" label="DNS" />
                  <StatusDot status="ok" label="Proxy" />
                  <StatusDot status={tlsStatus} label="TLS" />
                  <StatusDot status={ddnsStatus2} label="DDNS" />
                </div>
              </div>
            </button>

            {isExpanded && (
              <CardContent className="pt-0 pb-4 px-4 space-y-3">
                <div className="border rounded-lg divide-y text-sm ml-6">
                  <div className="flex items-center justify-between px-3 py-1.5">
                    <span className="text-muted-foreground">DNS (LAN)</span>
                    <span className="font-mono text-xs">
                      {service.backend.type === 'tcp-passthrough'
                        ? `→ ${service.backend.address.split(':')[0]}`
                        : `→ ${globalConfig?.cloud?.dnsmasq?.ip ?? '(Central IP)'}`}
                    </span>
                  </div>
                  {service.reach === 'public' && (
                    <div className="flex items-center justify-between px-3 py-1.5">
                      <span className="text-muted-foreground">DNS (Public)</span>
                      <span className="font-mono text-xs">A record → {publicIp ?? '—'}</span>
                    </div>
                  )}
                  <div className="flex items-center justify-between px-3 py-1.5">
                    <span className="text-muted-foreground">Proxy</span>
                    <span className="font-mono text-xs">{getProxyLabel(service)}</span>
                  </div>
                  <div className="flex items-center justify-between px-3 py-1.5">
                    <span className="text-muted-foreground">TLS</span>
                    <span className="font-mono text-xs">{getTlsLabel(service, certDomains)}</span>
                  </div>
                </div>

                <div className="flex items-center justify-between ml-6 text-xs text-muted-foreground">
                  <div className="flex gap-4">
                    <span>Backend: <span className="font-mono text-foreground">{service.backend.address}</span></span>
                    <span>Source: <span className="text-foreground">{service.source}</span></span>
                  </div>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-7 text-xs text-red-500 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950/20"
                    onClick={(e) => { e.stopPropagation(); deregisterMutation.mutate(service.domain); }}
                    disabled={deregisterMutation.isPending}
                  >
                    {deregisterMutation.isPending ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : <Trash2 className="h-3 w-3 mr-1" />}
                    Deregister
                  </Button>
                </div>
              </CardContent>
            )}
          </Card>
        );
      })}

      {/* Advanced */}
      <Collapsible open={showAdvanced} onOpenChange={handleShowAdvanced}>
        <Card>
          <CollapsibleTrigger asChild>
            <button type="button" className="flex items-center justify-between w-full text-left px-4 py-3">
              <span className="text-sm font-medium">Advanced</span>
              {loadingAdvanced ? <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
                : showAdvanced ? <ChevronUp className="h-4 w-4 text-muted-foreground" />
                : <ChevronDown className="h-4 w-4 text-muted-foreground" />}
            </button>
          </CollapsibleTrigger>
          <CollapsibleContent>
            <CardContent className="space-y-4 pt-0">
              <div className="flex gap-2">
                <Button onClick={() => generateHaproxy()} disabled={isHaproxyGenerating} size="sm" className="gap-1">
                  {isHaproxyGenerating ? <Loader2 className="h-3 w-3 animate-spin" /> : <Play className="h-3 w-3" />}
                  Generate & Apply
                </Button>
                <Button variant="outline" onClick={() => restartHaproxy()} disabled={isHaproxyRestarting} size="sm" className="gap-1">
                  {isHaproxyRestarting ? <Loader2 className="h-3 w-3 animate-spin" /> : <RotateCw className="h-3 w-3" />}
                  Restart HAProxy
                </Button>
              </div>
              {haproxyGenerateData && (
                <Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
                  <CheckCircle className="h-4 w-4 text-green-600" />
                  <AlertDescription className="text-green-700 dark:text-green-300">{haproxyGenerateData.message}</AlertDescription>
                </Alert>
              )}
              {haproxyGenerateError && (
                <Alert variant="error"><AlertCircle className="h-4 w-4" /><AlertDescription>{(haproxyGenerateError as Error).message}</AlertDescription></Alert>
              )}
              <Textarea value={advancedConfig} readOnly className="font-mono text-xs min-h-[200px]" placeholder="# haproxy configuration" />
            </CardContent>
          </CollapsibleContent>
        </Card>
      </Collapsible>
    </div>
  );
}
