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 { Switch } from './ui/switch';
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from './ui/collapsible';
import {
  Globe, Loader2, AlertCircle, CheckCircle, Play, RotateCw,
  Plus, Trash2, X, ChevronDown, ChevronUp,
} from 'lucide-react';
import { useHaproxy } from '../hooks/useHaproxy';
import { useServices } from '../hooks/useServices';
import { useCert } from '../hooks/useCert';
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' {
  if (service.tls === 'passthrough' || service.backend.type === 'tcp-passthrough') return 'na';
  return certDomains.has(service.domain) ? 'ok' : 'error';
}

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

  const [expandedDomains, setExpandedDomains] = useState<Set<string>>(new Set());
  const [showAddForm, setShowAddForm] = useState(false);
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [advancedConfig, setAdvancedConfig] = useState('');
  const [loadingAdvanced, setLoadingAdvanced] = useState(false);

  // Add form state
  const [newDomain, setNewDomain] = useState('');
  const [newBackendAddr, setNewBackendAddr] = useState('');
  const [newPublic, setNewPublic] = useState(true);
  const [newSubdomains, setNewSubdomains] = useState(false);
  const [newTls, setNewTls] = useState<string>('passthrough');

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

  const registerMutation = useMutation({
    mutationFn: (svc: Record<string, unknown>) => servicesApi.register(svc as any),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['services'] });
      setShowAddForm(false);
      setNewDomain(''); setNewBackendAddr(''); setNewPublic(true); setNewSubdomains(false); setNewTls('passthrough');
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({ domain, updates }: { domain: string; updates: Record<string, unknown> }) =>
      servicesApi.register({ ...(services.find(s => s.domain === domain) ?? {}), ...updates } as any),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['services'] }),
  });

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

  usePageHelp({
    title: 'Services',
    description: (
      <p className="leading-relaxed">
        Each service is a domain that Wild Central manages. Central provides DNS resolution,
        proxy routing, TLS certificates, and public DNS records based on how you configure each service.
      </p>
    ),
  });

  const toggleExpand = (domain: string) => {
    setExpandedDomains(prev => {
      const next = new Set(prev);
      if (next.has(domain)) next.delete(domain); else next.add(domain);
      return next;
    });
  };

  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">
      {/* 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 Form */}
      {showAddForm && (
        <Card className="border-dashed border-primary/50">
          <CardContent className="p-4 space-y-4">
            <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>
            <div className="flex items-center gap-6">
              <label className="flex items-center gap-2 text-sm">
                <Switch checked={newPublic} onCheckedChange={setNewPublic} />
                Public
              </label>
              <label className="flex items-center gap-2 text-sm">
                <Switch checked={newSubdomains} onCheckedChange={setNewSubdomains} />
                Include subdomains
              </label>
              <label className="flex items-center gap-2 text-sm">
                <Switch checked={newTls === 'terminate'} onCheckedChange={v => setNewTls(v ? 'terminate' : 'passthrough')} />
                Central handles TLS
              </label>
            </div>
            <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: newTls === 'passthrough' ? 'tcp-passthrough' : 'http' },
                  public: newPublic, subdomains: newSubdomains, tls: newTls, 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 */}
      {!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">Services appear when Wild Cloud or Wild Works registers domains, or add one manually.</p>
        </Card>
      )}

      {/* Service Cards */}
      {services.map(service => {
        const isExpanded = expandedDomains.has(service.domain);
        const tlsStatus = getTlsStatus(service, certDomains);
        const ddnsStatus2 = service.public ? 'ok' as const : 'na' as const;
        const isPassthrough = service.tls === 'passthrough' || service.backend.type === 'tcp-passthrough';

        return (
          <Card key={service.domain}>
            {/* Header — always visible */}
            <button type="button" onClick={() => toggleExpand(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">
                  <span className="font-mono text-sm font-medium truncate">
                    {service.subdomains ? `*.${service.domain}` : service.domain}
                  </span>
                </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>

            {/* Expanded — controls + status */}
            {isExpanded && (
              <CardContent className="pt-0 pb-4 px-4 space-y-4">
                {/* Controls */}
                <div className="flex flex-wrap items-center gap-x-6 gap-y-3 py-2">
                  <div>
                    <Label className="text-xs text-muted-foreground">Backend</Label>
                    <Input
                      defaultValue={service.backend.address}
                      className="mt-0.5 h-8 font-mono text-sm w-48"
                      onBlur={e => {
                        const val = e.target.value.trim();
                        if (val && val !== service.backend.address) {
                          updateMutation.mutate({
                            domain: service.domain,
                            updates: { backend: { ...service.backend, address: val } },
                          });
                        }
                      }}
                    />
                  </div>

                  <div className="flex items-center gap-2">
                    <Switch
                      checked={service.public}
                      onCheckedChange={v => updateMutation.mutate({ domain: service.domain, updates: { public: v } })}
                      disabled={updateMutation.isPending}
                    />
                    <Label className="text-sm">{service.public ? 'Public' : 'Private'}</Label>
                  </div>

                  <div className="flex items-center gap-2">
                    <Switch
                      checked={service.subdomains}
                      onCheckedChange={v => updateMutation.mutate({ domain: service.domain, updates: { subdomains: v } })}
                      disabled={updateMutation.isPending}
                    />
                    <Label className="text-sm">Subdomains</Label>
                  </div>

                  <div className="flex items-center gap-2">
                    <Switch
                      checked={!isPassthrough}
                      onCheckedChange={v => updateMutation.mutate({
                        domain: service.domain,
                        updates: {
                          tls: v ? 'terminate' : 'passthrough',
                          backend: { ...service.backend, type: v ? 'http' : 'tcp-passthrough' },
                        },
                      })}
                      disabled={updateMutation.isPending}
                    />
                    <Label className="text-sm">{isPassthrough ? 'TLS Passthrough' : 'Central TLS'}</Label>
                  </div>
                </div>

                {/* Source + deregister */}
                <div className="flex items-center justify-between text-xs text-muted-foreground">
                  <span>Source: {service.source}</span>
                  <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}>
                    <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]" />
            </CardContent>
          </CollapsibleContent>
        </Card>
      </Collapsible>
    </div>
  );
}
