<script setup lang="ts">
import { ref } from "vue";
import {
  Check,
  ChevronDown,
  ChevronUp,
  Clipboard,
  ExternalLink,
} from "lucide-vue-next";
import Badge from "../../components/ui/Badge.vue";
import Button from "../../components/ui/Button.vue";
import Card from "../../components/ui/Card.vue";
import CardContent from "../../components/ui/CardContent.vue";
import CardHeader from "../../components/ui/CardHeader.vue";
import CardTitle from "../../components/ui/CardTitle.vue";
import PageHeader from "../../components/PageHeader.vue";
import SettingsTabBar from "../../components/SettingsTabBar.vue";
import { useTranslations } from "../../composables/useTranslations";

const { t } = useTranslations();

interface EnvironmentInfo {
  laravel_version: string;
  builder_version: string;
  app_env: string;
  debug_mode: boolean;
  app_timezone: string;
  app_locale: string;
  config_cached: boolean;
  routes_cached: boolean;
  events_cached: boolean;
}

interface PhpInfo {
  version: string;
  memory_limit: string;
  upload_max_size: string;
  post_max_size: string;
  max_execution: string;
  opcache_enabled: boolean;
  extensions: string[];
}

interface ServerInfo {
  software: string;
  os: string;
}

interface DatabaseInfo {
  driver: string;
  version: string | null;
  name: string | null;
  size: number | null;
}

interface CacheInfo {
  cache_driver: string;
  session_driver: string;
}

interface QueueInfo {
  driver: string;
  pending: number | null;
  failed: number | null;
  horizon: boolean;
}

interface StorageInfo {
  app_size: number;
  log_size: number;
}

interface ModuleInfo {
  key: string;
  label: string;
  version: string | null;
  author: string | null;
  author_url: string | null;
}

const props = defineProps<{
  environment: EnvironmentInfo;
  php: PhpInfo;
  server: ServerInfo;
  database: DatabaseInfo;
  cacheAndSession: CacheInfo;
  queue: QueueInfo;
  storage: StorageInfo;
  modules: ModuleInfo[];
}>();

const extensionsExpanded = ref(false);
const copied = ref(false);

function formatBytes(bytes: number): string {
  if (bytes === 0) {
    return "0 B";
  }
  const units = ["B", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${units[i]}`;
}

function mdTable(rows: [string, string][]): string {
  const lines = ["| Key | Value |", "|---|---|"];
  for (const [k, v] of rows) {
    lines.push(`| ${k} | ${v} |`);
  }
  return lines.join("\n");
}

function buildMarkdown(): string {
  const e = props.environment;
  const p = props.php;
  const s = props.server;
  const db = props.database;
  const c = props.cacheAndSession;
  const q = props.queue;
  const st = props.storage;

  const sections: string[] = [
    `# Application Health\n`,

    `## Environment\n${mdTable([
      ["Laravel version", e.laravel_version],
      ["Builder version", e.builder_version],
      ["Environment", e.app_env],
      ["Debug mode", e.debug_mode ? "Enabled" : "Disabled"],
      ["Timezone", e.app_timezone],
      ["Locale", e.app_locale],
      ["Config cached", e.config_cached ? "Yes" : "No"],
      ["Routes cached", e.routes_cached ? "Yes" : "No"],
      ["Events cached", e.events_cached ? "Yes" : "No"],
    ])}`,

    `## PHP\n${mdTable([
      ["Version", p.version],
      ["Memory limit", p.memory_limit],
      ["Upload max size", p.upload_max_size],
      ["Post max size", p.post_max_size],
      ["Max execution time", `${p.max_execution}s`],
      ["OPcache", p.opcache_enabled ? "Enabled" : "Disabled"],
      ["Extensions", p.extensions.join(", ")],
    ])}`,

    `## Server\n${mdTable([
      ["Web server", s.software],
      ["Operating system", s.os],
    ])}`,

    `## Database\n${mdTable([
      ["Driver", db.driver],
      ...(db.version ? [["Version", db.version] as [string, string]] : []),
      ...(db.name ? [["Database", db.name] as [string, string]] : []),
      ...(db.size !== null
        ? [["Size", formatBytes(db.size)] as [string, string]]
        : []),
    ])}`,

    `## Cache & Session\n${mdTable([
      ["Cache driver", c.cache_driver],
      ["Session driver", c.session_driver],
    ])}`,

    `## Queue\n${mdTable([
      ["Driver", q.driver],
      ...(q.pending !== null
        ? [["Pending jobs", String(q.pending)] as [string, string]]
        : []),
      ...(q.failed !== null
        ? [["Failed jobs", String(q.failed)] as [string, string]]
        : []),
      ["Horizon", q.horizon ? "Installed" : "Not installed"],
    ])}`,

    `## Storage\n${mdTable([
      ["Application storage", formatBytes(st.app_size)],
      ["Log file size", formatBytes(st.log_size)],
      ["Total", formatBytes(st.app_size + st.log_size)],
    ])}`,

    `## Modules\n| Module | Version | Author |\n|---|---|---|\n${props.modules
      .map((m) => `| ${m.label} | ${m.version ?? "—"} | ${m.author ?? "—"} |`)
      .join("\n")}`,
  ];

  return sections.join("\n\n");
}

function copyToMarkdown(): void {
  navigator.clipboard.writeText(buildMarkdown()).then(() => {
    copied.value = true;
    setTimeout(() => {
      copied.value = false;
    }, 2000);
  });
}

const showDebugWarning =
  props.environment.app_env === "production" && props.environment.debug_mode;
</script>

<template>
  <div>
    <PageHeader :title="t('builder.nav.health')">
      <template #actions>
        <Button variant="outline" size="sm" @click="copyToMarkdown">
          <Check v-if="copied" class="mr-1.5 h-3.5 w-3.5 text-green-600" />
          <Clipboard v-else class="mr-1.5 h-3.5 w-3.5" />
          {{ copied ? "Copied!" : "Copy" }}
        </Button>
      </template>
    </PageHeader>

    <SettingsTabBar />

    <div
      v-if="showDebugWarning"
      class="mb-4 rounded-lg border border-destructive/50 bg-destructive/10 p-3"
    >
      <p class="text-sm font-medium text-destructive">
        Debug mode is enabled in a production environment. This may expose
        sensitive application information.
      </p>
    </div>

    <div class="grid grid-cols-1 gap-3 lg:grid-cols-2">
      <!-- Environment -->
      <Card>
        <CardHeader class="p-4 pb-2">
          <CardTitle class="text-sm font-semibold">Environment</CardTitle>
        </CardHeader>
        <CardContent class="px-4 pb-4 pt-0">
          <table class="w-full text-sm">
            <tbody class="divide-y">
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Laravel version</td>
                <td class="font-mono text-xs">
                  {{ environment.laravel_version }}
                </td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Builder version</td>
                <td class="font-mono text-xs">
                  {{ environment.builder_version }}
                </td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Environment</td>
                <td>
                  <Badge
                    :variant="
                      environment.app_env === 'production'
                        ? 'default'
                        : 'secondary'
                    "
                    class="text-xs"
                  >
                    {{ environment.app_env }}
                  </Badge>
                </td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Debug mode</td>
                <td>
                  <Badge
                    :variant="
                      environment.debug_mode ? 'destructive' : 'secondary'
                    "
                    class="text-xs"
                  >
                    {{ environment.debug_mode ? "Enabled" : "Disabled" }}
                  </Badge>
                </td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Timezone</td>
                <td class="font-mono text-xs">
                  {{ environment.app_timezone }}
                </td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Locale</td>
                <td class="font-mono text-xs">{{ environment.app_locale }}</td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Config cached</td>
                <td>
                  <Badge
                    :variant="environment.config_cached ? 'default' : 'outline'"
                    class="text-xs"
                  >
                    {{ environment.config_cached ? "Yes" : "No" }}
                  </Badge>
                </td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Routes cached</td>
                <td>
                  <Badge
                    :variant="environment.routes_cached ? 'default' : 'outline'"
                    class="text-xs"
                  >
                    {{ environment.routes_cached ? "Yes" : "No" }}
                  </Badge>
                </td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Events cached</td>
                <td>
                  <Badge
                    :variant="environment.events_cached ? 'default' : 'outline'"
                    class="text-xs"
                  >
                    {{ environment.events_cached ? "Yes" : "No" }}
                  </Badge>
                </td>
              </tr>
            </tbody>
          </table>
        </CardContent>
      </Card>

      <!-- PHP -->
      <Card>
        <CardHeader class="p-4 pb-2">
          <CardTitle class="text-sm font-semibold">PHP</CardTitle>
        </CardHeader>
        <CardContent class="px-4 pb-4 pt-0">
          <table class="w-full text-sm">
            <tbody class="divide-y">
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">PHP version</td>
                <td class="font-mono text-xs">{{ php.version }}</td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Memory limit</td>
                <td class="font-mono text-xs">{{ php.memory_limit }}</td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Upload max size</td>
                <td class="font-mono text-xs">{{ php.upload_max_size }}</td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Post max size</td>
                <td class="font-mono text-xs">{{ php.post_max_size }}</td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Max execution time</td>
                <td class="font-mono text-xs">{{ php.max_execution }}s</td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">OPcache</td>
                <td>
                  <Badge
                    :variant="php.opcache_enabled ? 'default' : 'secondary'"
                    class="text-xs"
                  >
                    {{ php.opcache_enabled ? "Enabled" : "Disabled" }}
                  </Badge>
                </td>
              </tr>
            </tbody>
          </table>

          <div class="mt-3 border-t pt-3">
            <button
              type="button"
              class="flex w-full items-center justify-between text-sm"
              @click="extensionsExpanded = !extensionsExpanded"
            >
              <span class="text-muted-foreground">
                Loaded extensions ({{ php.extensions.length }})
              </span>
              <ChevronUp
                v-if="extensionsExpanded"
                class="h-4 w-4 text-muted-foreground"
              />
              <ChevronDown v-else class="h-4 w-4 text-muted-foreground" />
            </button>
            <div v-if="extensionsExpanded" class="mt-2 flex flex-wrap gap-1">
              <Badge
                v-for="ext in php.extensions"
                :key="ext"
                variant="outline"
                class="font-mono text-xs"
              >
                {{ ext }}
              </Badge>
            </div>
          </div>
        </CardContent>
      </Card>

      <!-- Server -->
      <Card>
        <CardHeader class="p-4 pb-2">
          <CardTitle class="text-sm font-semibold">Server</CardTitle>
        </CardHeader>
        <CardContent class="px-4 pb-4 pt-0">
          <table class="w-full text-sm">
            <tbody class="divide-y">
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Web server</td>
                <td class="font-mono text-xs">{{ server.software }}</td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Operating system</td>
                <td class="font-mono text-xs">{{ server.os }}</td>
              </tr>
            </tbody>
          </table>
        </CardContent>
      </Card>

      <!-- Database -->
      <Card>
        <CardHeader class="p-4 pb-2">
          <CardTitle class="text-sm font-semibold">Database</CardTitle>
        </CardHeader>
        <CardContent class="px-4 pb-4 pt-0">
          <table class="w-full text-sm">
            <tbody class="divide-y">
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Driver</td>
                <td class="font-mono text-xs">{{ database.driver }}</td>
              </tr>
              <tr
                v-if="database.version"
                class="flex items-center justify-between py-1.5"
              >
                <td class="text-muted-foreground">Version</td>
                <td class="font-mono text-xs">{{ database.version }}</td>
              </tr>
              <tr
                v-if="database.name"
                class="flex items-center justify-between py-1.5"
              >
                <td class="text-muted-foreground">Database</td>
                <td class="font-mono text-xs">{{ database.name }}</td>
              </tr>
              <tr
                v-if="database.size !== null"
                class="flex items-center justify-between py-1.5"
              >
                <td class="text-muted-foreground">Database size</td>
                <td class="font-mono text-xs">
                  {{ formatBytes(database.size) }}
                </td>
              </tr>
            </tbody>
          </table>
        </CardContent>
      </Card>

      <!-- Cache & Session -->
      <Card>
        <CardHeader class="p-4 pb-2">
          <CardTitle class="text-sm font-semibold"
            >Cache &amp; Session</CardTitle
          >
        </CardHeader>
        <CardContent class="px-4 pb-4 pt-0">
          <table class="w-full text-sm">
            <tbody class="divide-y">
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Cache driver</td>
                <td class="font-mono text-xs">
                  {{ cacheAndSession.cache_driver }}
                </td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Session driver</td>
                <td class="font-mono text-xs">
                  {{ cacheAndSession.session_driver }}
                </td>
              </tr>
            </tbody>
          </table>
        </CardContent>
      </Card>

      <!-- Queue -->
      <Card>
        <CardHeader class="p-4 pb-2">
          <CardTitle class="text-sm font-semibold">Queue</CardTitle>
        </CardHeader>
        <CardContent class="px-4 pb-4 pt-0">
          <table class="w-full text-sm">
            <tbody class="divide-y">
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Driver</td>
                <td class="font-mono text-xs">{{ queue.driver }}</td>
              </tr>
              <tr
                v-if="queue.pending !== null"
                class="flex items-center justify-between py-1.5"
              >
                <td class="text-muted-foreground">Pending jobs</td>
                <td>
                  <Badge variant="secondary" class="font-mono text-xs">
                    {{ queue.pending }}
                  </Badge>
                </td>
              </tr>
              <tr
                v-if="queue.failed !== null"
                class="flex items-center justify-between py-1.5"
              >
                <td class="text-muted-foreground">Failed jobs</td>
                <td>
                  <Badge
                    :variant="queue.failed > 0 ? 'destructive' : 'secondary'"
                    class="font-mono text-xs"
                  >
                    {{ queue.failed }}
                  </Badge>
                </td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Horizon</td>
                <td>
                  <Badge
                    :variant="queue.horizon ? 'default' : 'outline'"
                    class="text-xs"
                  >
                    {{ queue.horizon ? "Installed" : "Not installed" }}
                  </Badge>
                </td>
              </tr>
            </tbody>
          </table>
        </CardContent>
      </Card>

      <!-- Storage -->
      <Card>
        <CardHeader class="p-4 pb-2">
          <CardTitle class="text-sm font-semibold">Storage</CardTitle>
        </CardHeader>
        <CardContent class="px-4 pb-4 pt-0">
          <table class="w-full text-sm">
            <tbody class="divide-y">
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Application storage</td>
                <td class="font-mono text-xs">
                  {{ formatBytes(storage.app_size) }}
                </td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Log file size</td>
                <td class="font-mono text-xs">
                  {{ formatBytes(storage.log_size) }}
                </td>
              </tr>
              <tr class="flex items-center justify-between py-1.5">
                <td class="text-muted-foreground">Total</td>
                <td class="font-mono text-xs font-semibold">
                  {{ formatBytes(storage.app_size + storage.log_size) }}
                </td>
              </tr>
            </tbody>
          </table>
        </CardContent>
      </Card>

      <!-- Modules -->
      <Card>
        <CardHeader class="p-4 pb-2">
          <CardTitle class="text-sm font-semibold">Installed modules</CardTitle>
        </CardHeader>
        <CardContent class="px-4 pb-4 pt-0">
          <table class="w-full text-sm">
            <thead>
              <tr
                class="flex items-center gap-4 pb-1.5 text-xs font-medium text-muted-foreground"
              >
                <th class="flex-1 text-left font-medium">Module</th>
                <th class="w-24 text-left font-medium">Version</th>
                <th class="w-40 text-left font-medium">Author</th>
              </tr>
            </thead>
            <tbody class="divide-y">
              <tr
                v-for="mod in modules"
                :key="mod.key"
                class="flex items-center gap-4 py-1.5"
              >
                <td class="flex-1 font-medium">{{ mod.label }}</td>
                <td class="w-24 font-mono text-xs text-muted-foreground">
                  {{ mod.version ?? "—" }}
                </td>
                <td class="w-40 text-xs text-muted-foreground">
                  <a
                    v-if="mod.author_url"
                    :href="mod.author_url"
                    target="_blank"
                    rel="noopener noreferrer"
                    class="inline-flex items-center gap-1 hover:text-foreground hover:underline"
                  >
                    {{ mod.author ?? "—" }}
                    <ExternalLink class="h-3 w-3" />
                  </a>
                  <span v-else>{{ mod.author ?? "—" }}</span>
                </td>
              </tr>
            </tbody>
          </table>
        </CardContent>
      </Card>
    </div>
  </div>
</template>
