import { Activity, CheckCircle2, FileText, FolderX, Lightbulb, Pencil, PlayCircle, RefreshCw, XCircle } from 'lucide-react';

import { useState } from 'react';

import { Link, router } from '@inertiajs/react';

import AdminPage from '@/Components/admin/AdminPage';
import { AdminStatsGrid, type StatCard } from '@/Components/admin/AdminStatsGrid';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/Components/ui/card';
import { ConfirmDialog } from '@/Components/ui/confirm-dialog';
import { CopyButton } from '@/Components/ui/copy-button';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { RelativeTime } from '@/Components/ui/relative-time';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/Components/ui/tabs';
import { useMutationButton } from '@/hooks/useMutationButton';
import AdminLayout from '@/Layouts/AdminLayout';
import { getAdminStatusVariant } from '@/lib/adminStatusBadge';
import { formatDate } from '@/lib/format';

interface SiteDetail {
  id: number;
  name: string;
  domain: string;
  user_id: number;
  health_score: string | null;
  health_status: string;
  created_at: string;
  deleted_at: string | null;
  user: { id: number; name: string; email: string } | null;
}

interface AnalysisRunRow {
  id: number;
  status: string;
  created_at: string | null;
  completed_at: string | null;
  summary: Record<string, unknown> | null;
}

interface RecommendationRow {
  id: number;
  action_type: string;
  lifecycle_status: string;
  impact_score: number;
  created_at: string | null;
}

interface WpPostRow {
  id: number;
  title: string;
  url: string;
  post_status: string | null;
  word_count: number | null;
  wp_modified_at: string | null;
}

interface Connections {
  gsc: { id: number; sync_status: string; last_synced_at: string | null } | null;
  wp: { wp_url: string } | null;
}

interface SiteStats {
  recommendation_count: number;
  draft_count: number;
  wp_post_count: number;
  analysis_run_count: number;
}

interface SiteShowProps {
  site: SiteDetail;
  analysis_runs: AnalysisRunRow[];
  connections: Connections;
  recent_recommendations: RecommendationRow[];
  wp_posts: WpPostRow[];
  stats: SiteStats;
}

export default function AdminSitesShow({
  site,
  analysis_runs,
  connections,
  recent_recommendations,
  wp_posts,
  stats,
}: SiteShowProps) {
  const [restoreOpen, setRestoreOpen] = useState(false);
  const [editing, setEditing] = useState(false);
  const [editName, setEditName] = useState(site.name);
  const [editDomain, setEditDomain] = useState(site.domain);

  const { processing: isSaving, onClick: handleSave } = useMutationButton(
    (opts) => router.patch(
      route('admin.sites.update', site.id),
      { name: editName, domain: editDomain },
      { ...opts, preserveScroll: true, onSuccess: () => setEditing(false) },
    ),
  );

  const handleRestore = (): Promise<void> =>
    new Promise<void>((resolve, reject) => {
      router.post(route('admin.sites.restore', site.id), {}, {
        onSuccess: () => { setRestoreOpen(false); resolve(); },
        onError: () => reject(),
      });
    });

  const handleCancelEdit = () => {
    setEditName(site.name);
    setEditDomain(site.domain);
    setEditing(false);
  };

  const statCards: StatCard[] = [
    { title: 'Analysis Runs', value: stats.analysis_run_count, icon: Activity },
    { title: 'Recommendations', value: stats.recommendation_count, icon: Lightbulb },
    { title: 'AI Drafts', value: stats.draft_count, icon: FileText },
    { title: 'WP Posts', value: stats.wp_post_count, icon: FileText },
  ];

  return (
    <AdminLayout>
      <AdminPage
        title={site.name}
        subtitle={site.domain}
        breadcrumbs={[
          { label: 'Admin', href: '/admin' },
          { label: 'Sites', href: '/admin/sites' },
          // F4ADMINUX-010: Owner breadcrumb deep-link
          ...(site.user
            ? [{ label: site.user.name, href: `/admin/users/${site.user.id}` }]
            : []),
          { label: site.name },
        ]}
        actions={
          <div className="flex items-center gap-2">
            {/* F4ADMINUX-010: DLQ deep-link for this site */}
            <Button
              variant="outline"
              size="sm"
              asChild
            >
              <a href={`/admin/dlq?site_id=${site.id}`}>
                <FolderX className="mr-1.5 size-3.5" />
                DLQ
              </a>
            </Button>
            {/* F4ADMINUX-010: Deep-link to analysis runs filtered for this site */}
            <Button
              variant="outline"
              size="sm"
              asChild
            >
              <a href={`/admin/analysis-runs?search=${encodeURIComponent(site.domain)}`}>
                <PlayCircle className="mr-1.5 size-3.5" />
                Runs
              </a>
            </Button>
            {/* F4ADMINUX-010: Trigger GSC sync */}
            {connections.gsc && (
              <Button
                variant="outline"
                size="sm"
                onClick={() => router.post(route('admin.gsc-connections.sync', { gscConnection: connections.gsc!.id }), {})}
              >
                <RefreshCw className="mr-1.5 size-3.5" />
                Sync GSC
              </Button>
            )}
            {!editing && (
              <Button variant="outline" size="sm" onClick={() => setEditing(true)}>
                <Pencil className="mr-1.5 size-3.5" />
                Edit
              </Button>
            )}
            {site.deleted_at && (
              <Button variant="outline" onClick={() => setRestoreOpen(true)}>
                Restore Site
              </Button>
            )}
          </div>
        }
      >
        {editing && (
          <Card>
            <CardHeader>
              <CardTitle className="text-sm font-medium">Edit Site</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-4 sm:grid-cols-2">
                <div className="space-y-1.5">
                  <Label htmlFor="edit-name">Name</Label>
                  <Input
                    id="edit-name"
                    value={editName}
                    onChange={(e) => setEditName(e.target.value)}
                    placeholder="Site name"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label htmlFor="edit-domain">Domain</Label>
                  <Input
                    id="edit-domain"
                    value={editDomain}
                    onChange={(e) => setEditDomain(e.target.value)}
                    placeholder="https://example.com"
                  />
                </div>
              </div>
              <div className="flex gap-2">
                <Button size="sm" onClick={handleSave} disabled={isSaving}>
                  {isSaving ? 'Saving…' : 'Save'}
                </Button>
                <Button variant="ghost" size="sm" onClick={handleCancelEdit}>
                  Cancel
                </Button>
              </div>
            </CardContent>
          </Card>
        )}

        {site.deleted_at && (
          <div className="rounded-lg border border-destructive bg-destructive/5 p-4">
            <p className="text-sm font-medium text-destructive">
              This site was deleted on {formatDate(site.deleted_at)}.
            </p>
          </div>
        )}

        <AdminStatsGrid stats={statCards} />

        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          <Card>
            <CardHeader>
              <CardTitle className="text-sm font-medium">Site Info</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-muted-foreground">Domain</span>
                <span className="flex items-center gap-1">
                  {site.domain}
                  <CopyButton value={site.domain} />
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">Health</span>
                <span>
                  {site.health_score !== null
                    ? `${parseFloat(site.health_score).toFixed(0)} - ${site.health_status}`
                    : 'Unknown'}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">Created</span>
                <RelativeTime value={site.created_at} />
              </div>
              {site.user && (
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Owner</span>
                  <span className="flex items-center gap-1">
                    <Link href={`/admin/users/${site.user.id}`} className="hover:underline">
                      {site.user.email}
                    </Link>
                    <CopyButton value={site.user.email} />
                  </span>
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="text-sm font-medium flex items-center gap-2">
                GSC Connection
                {connections.gsc ? (
                  <CheckCircle2 className="size-4 text-success" />
                ) : (
                  <XCircle className="size-4 text-muted-foreground" />
                )}
              </CardTitle>
            </CardHeader>
            <CardContent className="text-sm">
              {connections.gsc ? (
                <div className="space-y-2">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Status</span>
                    <Badge variant={getAdminStatusVariant(connections.gsc.sync_status)}>
                      {connections.gsc.sync_status}
                    </Badge>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Last Synced</span>
                    <RelativeTime value={connections.gsc.last_synced_at} />
                  </div>
                </div>
              ) : (
                <p className="text-muted-foreground">Not connected</p>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="text-sm font-medium flex items-center gap-2">
                WP Connection
                {connections.wp ? (
                  <CheckCircle2 className="size-4 text-success" />
                ) : (
                  <XCircle className="size-4 text-muted-foreground" />
                )}
              </CardTitle>
            </CardHeader>
            <CardContent className="text-sm">
              {connections.wp ? (
                <div className="flex justify-between">
                  <span className="text-muted-foreground">URL</span>
                  <span className="truncate max-w-48">{connections.wp.wp_url}</span>
                </div>
              ) : (
                <p className="text-muted-foreground">Not connected</p>
              )}
            </CardContent>
          </Card>
        </div>

        <Tabs defaultValue="analysis">
          <TabsList>
            <TabsTrigger value="analysis">Analysis Runs</TabsTrigger>
            <TabsTrigger value="recommendations">Recommendations</TabsTrigger>
            <TabsTrigger value="wp-posts">WP Posts</TabsTrigger>
          </TabsList>

          <TabsContent value="analysis">
            <Card>
              <CardHeader>
                <CardTitle className="text-sm font-medium">Analysis History (Last 20)</CardTitle>
              </CardHeader>
              <CardContent>
                {analysis_runs.length === 0 ? (
                  <p className="text-sm text-muted-foreground py-4 text-center">
                    No analysis runs yet.
                  </p>
                ) : (
                  <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>ID</TableHead>
                        <TableHead>Status</TableHead>
                        <TableHead>Started</TableHead>
                        <TableHead>Completed</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {analysis_runs.map((run) => (
                        <TableRow key={run.id}>
                          <TableCell className="font-mono text-xs">#{run.id}</TableCell>
                          <TableCell>
                            <Badge variant={getAdminStatusVariant(run.status)}>
                              {run.status}
                            </Badge>
                          </TableCell>
                          <TableCell className="text-sm text-muted-foreground">
                            <RelativeTime value={run.created_at} />
                          </TableCell>
                          <TableCell className="text-sm text-muted-foreground">
                            <RelativeTime value={run.completed_at} />
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="recommendations">
            <Card>
              <CardHeader>
                <CardTitle className="text-sm font-medium">
                  Recent Recommendations (Last 20)
                </CardTitle>
              </CardHeader>
              <CardContent>
                {recent_recommendations.length === 0 ? (
                  <p className="text-sm text-muted-foreground py-4 text-center">
                    No recommendations yet.
                  </p>
                ) : (
                  <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>ID</TableHead>
                        <TableHead>Action Type</TableHead>
                        <TableHead>Status</TableHead>
                        <TableHead>Impact</TableHead>
                        <TableHead>Created</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {recent_recommendations.map((rec) => (
                        <TableRow key={rec.id}>
                          <TableCell className="font-mono text-xs">#{rec.id}</TableCell>
                          <TableCell className="text-sm">
                            {rec.action_type.replace(/_/g, ' ')}
                          </TableCell>
                          <TableCell>
                            <Badge variant={getAdminStatusVariant(rec.lifecycle_status)}>
                              {rec.lifecycle_status}
                            </Badge>
                          </TableCell>
                          <TableCell className="text-sm">{rec.impact_score}</TableCell>
                          <TableCell className="text-sm text-muted-foreground">
                            <RelativeTime value={rec.created_at} />
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="wp-posts">
            <Card>
              <CardHeader>
                <CardTitle className="text-sm font-medium">WP Posts (Last 20)</CardTitle>
              </CardHeader>
              <CardContent>
                {wp_posts.length === 0 ? (
                  <p className="text-sm text-muted-foreground py-4 text-center">
                    No WordPress posts synced.
                  </p>
                ) : (
                  <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Title</TableHead>
                        <TableHead>Status</TableHead>
                        <TableHead>Words</TableHead>
                        <TableHead>Modified</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {wp_posts.map((post) => (
                        <TableRow key={post.id}>
                          <TableCell>
                            <div>
                              <p className="text-sm font-medium truncate max-w-xs">{post.title}</p>
                              <p className="text-xs text-muted-foreground truncate max-w-xs">
                                {post.url}
                              </p>
                            </div>
                          </TableCell>
                          <TableCell>
                            <Badge variant={getAdminStatusVariant(post.post_status ?? '')}>
                              {post.post_status ?? '—'}
                            </Badge>
                          </TableCell>
                          <TableCell className="text-sm text-muted-foreground">
                            {post.word_count ?? '—'}
                          </TableCell>
                          <TableCell className="text-sm text-muted-foreground">
                            <RelativeTime value={post.wp_modified_at} />
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
        <ConfirmDialog
          open={restoreOpen}
          onOpenChange={setRestoreOpen}
          title="Restore this site?"
          description={`This will restore "${site.name}" and make it accessible again. The site's data and connections will remain intact.`}
          confirmLabel="Restore Site"
          onConfirm={handleRestore}
        />
      </AdminPage>
    </AdminLayout>
  );
}
