'use client';

import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { toast } from 'sonner';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Separator } from '@/components/ui/separator';
import {
  ArrowLeft,
  Copy,
  CheckCircle,
  XCircle,
  AlertTriangle,
  Clock,
  Info,
  FileText,
  User,
  Phone,
  Image as ImageIcon,
  Bell,
} from 'lucide-react';

interface OrderLog {
  id: string;
  orderId: string;
  level: string;
  message: string;
  createdAt: string;
}

interface Screenshot {
  id: string;
  orderId: string;
  fileName: string;
  fileSize: number;
  mimeType: string;
  createdAt: string;
}

interface NotifyLog {
  id: string;
  orderId: string;
  type: string;
  status: string;
  recipient: string | null;
  message: string;
  response: string | null;
  error: string | null;
  attempts: number;
  createdAt: string;
  updatedAt: string;
}

interface OrderDetail {
  id: string;
  mOrderId: string;
  payOrderId: string | null;
  amount: number;
  paidAmount: number;
  currency: string;
  status: 'PENDING' | 'SUCCESS' | 'FAILED' | 'SIGN_FAILED';
  paymentUrl: string | null;
  utr: string | null;
  sign: string | null;
  callbackPayload: string | null;
  signVerified: boolean;
  telegramSent: boolean;
  telegramError: string | null;
  customerName: string | null;
  customerMobile: string | null;
  gateway: string;
  createdAt: string;
  callbackAt: string | null;
  logs: OrderLog[];
  screenshots: Screenshot[];
  notifyLogs: NotifyLog[];
}

function getStatusBadge(status: string) {
  const map: Record<string, { label: string; variant: 'default' | 'secondary' | 'destructive' | 'outline'; className: string }> = {
    PENDING: { label: 'Pending', variant: 'secondary', className: 'bg-amber-100 text-amber-800 hover:bg-amber-100 border-amber-200' },
    SUCCESS: { label: 'Success', variant: 'default', className: 'bg-emerald-100 text-emerald-800 hover:bg-emerald-100 border-emerald-200' },
    FAILED: { label: 'Failed', variant: 'destructive', className: 'bg-red-100 text-red-800 hover:bg-red-100 border-red-200' },
    SIGN_FAILED: { label: 'Sign Failed', variant: 'destructive', className: 'bg-red-100 text-red-800 hover:bg-red-100 border-red-200' },
  };
  const config = map[status] || { label: status, variant: 'secondary' as const, className: '' };
  return <Badge variant={config.variant} className={config.className}>{config.label}</Badge>;
}

function getLogBadge(level: string) {
  const map: Record<string, { label: string; className: string }> = {
    INFO: { label: 'INFO', className: 'bg-blue-100 text-blue-800 border-blue-200' },
    WARN: { label: 'WARN', className: 'bg-amber-100 text-amber-800 border-amber-200' },
    ERROR: { label: 'ERROR', className: 'bg-red-100 text-red-800 border-red-200' },
    DEBUG: { label: 'DEBUG', className: 'bg-gray-100 text-gray-700 border-gray-300' },
  };
  const config = map[level] || { label: level, className: 'bg-gray-100 text-gray-700' };
  return <Badge variant="outline" className={config.className}>{config.label}</Badge>;
}

function getNotifyStatusBadge(status: string) {
  const map: Record<string, { label: string; className: string }> = {
    PENDING: { label: 'PENDING', className: 'bg-amber-100 text-amber-800 border-amber-200' },
    SENT: { label: 'SENT', className: 'bg-emerald-100 text-emerald-800 border-emerald-200' },
    FAILED: { label: 'FAILED', className: 'bg-red-100 text-red-800 border-red-200' },
  };
  const config = map[status] || { label: status, className: 'bg-gray-100 text-gray-700' };
  return <Badge variant="outline" className={config.className}>{config.label}</Badge>;
}

function formatDateTime(dateStr: string | null): string {
  if (!dateStr) return '\u2014';
  const date = new Date(dateStr);
  return date.toLocaleString('en-US', {
    year: 'numeric', month: 'short', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false,
  });
}

function CopyButton({ text, label }: { text: string | null; label: string }) {
  const [copied, setCopied] = useState(false);
  if (!text) return <span className="text-gray-400">\u2014</span>;
  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      toast.success(`${label} copied`);
      setTimeout(() => setCopied(false), 2000);
    } catch { toast.error('Failed to copy'); }
  };
  return (
    <div className="flex items-center gap-1.5">
      <span className="text-sm text-gray-900 font-mono break-all">{text}</span>
      <Button variant="ghost" size="icon" className="h-7 w-7 shrink-0 text-gray-400 hover:text-gray-600" onClick={handleCopy}>
        {copied ? <CheckCircle className="h-3.5 w-3.5 text-emerald-500" /> : <Copy className="h-3.5 w-3.5" />}
      </Button>
    </div>
  );
}

function JsonBlock({ title, data }: { title: string; data: string | null }) {
  const [copied, setCopied] = useState(false);
  if (!data) {
    return (
      <Card>
        <CardHeader className="pb-3"><CardTitle className="text-sm font-medium">{title}</CardTitle></CardHeader>
        <CardContent><p className="text-sm text-gray-400">No data available</p></CardContent>
      </Card>
    );
  }
  let formattedJson: string;
  try {
    formattedJson = JSON.stringify(typeof data === 'string' ? JSON.parse(data) : data, null, 2);
  } catch { formattedJson = data; }
  const handleCopy = async () => {
    try { await navigator.clipboard.writeText(formattedJson); setCopied(true); toast.success(`${title} copied`); setTimeout(() => setCopied(false), 2000); }
    catch { toast.error('Failed to copy'); }
  };
  return (
    <Card>
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardTitle className="text-sm font-medium">{title}</CardTitle>
          <Button variant="ghost" size="sm" className="h-7 text-xs text-gray-500 hover:text-gray-700 gap-1" onClick={handleCopy}>
            {copied ? <><CheckCircle className="h-3.5 w-3.5 text-emerald-500" /> Copied</> : <><Copy className="h-3.5 w-3.5" /> Copy</>}
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        <pre className="bg-gray-50 border rounded-lg p-4 overflow-x-auto text-xs leading-relaxed font-mono text-gray-800 max-h-96 overflow-y-auto">
          <code>{formattedJson}</code>
        </pre>
      </CardContent>
    </Card>
  );
}

function InfoRow({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="flex flex-col sm:flex-row sm:items-start gap-1 sm:gap-3 py-2">
      <span className="text-sm text-gray-500 shrink-0 sm:w-44">{label}</span>
      <div className="flex-1 min-w-0">{children}</div>
    </div>
  );
}

function LoadingSkeleton() {
  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4"><Skeleton className="h-9 w-9 rounded-lg" /><Skeleton className="h-8 w-48" /><Skeleton className="h-6 w-20" /></div>
      <Skeleton className="h-10 w-full max-w-md" />
      <div className="space-y-4">{Array.from({ length: 6 }).map((_, i) => <div key={i} className="flex items-start gap-3"><Skeleton className="h-4 w-36 shrink-0" /><Skeleton className="h-4 flex-1" /></div>)}</div>
    </div>
  );
}

export default function AdminOrderDetailPage() {
  const params = useParams();
  const router = useRouter();
  const [order, setOrder] = useState<OrderDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [expandedScreenshot, setExpandedScreenshot] = useState<string | null>(null);
  const id = params.id as string;

  useEffect(() => {
    if (!id) return;
    const fetchOrder = async () => {
      setLoading(true);
      setError(null);
      try {
        const res = await fetch(`/api/admin/orders/${id}`);
        if (!res.ok) setError(res.status === 404 ? 'Order not found' : 'Failed to fetch');
        else { const data = await res.json(); setOrder(data.order); }
      } catch { setError('Failed to fetch'); }
      finally { setLoading(false); }
    };
    fetchOrder();
  }, [id]);

  if (loading) return <div className="max-w-5xl mx-auto"><LoadingSkeleton /></div>;

  if (error || !order) {
    return (
      <div className="max-w-5xl mx-auto">
        <div className="flex items-center gap-4 mb-6">
          <Button variant="ghost" size="icon" asChild><Link href="/admin/orders"><ArrowLeft className="h-5 w-5" /></Link></Button>
          <h1 className="text-2xl font-bold text-gray-900">Order Details</h1>
        </div>
        <Card><CardContent className="py-12 flex flex-col items-center gap-3">
          <AlertTriangle className="h-10 w-10 text-amber-500" />
          <p className="text-gray-600 font-medium">{error || 'Order not found'}</p>
          <Button variant="outline" asChild><Link href="/admin/orders"><ArrowLeft className="h-4 w-4 mr-2" /> Back to Orders</Link></Button>
        </CardContent></Card>
      </div>
    );
  }

  const createRequestData = order.sign
    ? JSON.stringify({ mOrderId: order.mOrderId, amount: order.amount, currency: order.currency, customerName: order.customerName, customerMobile: order.customerMobile, sign: order.sign }, null, 2)
    : null;

  return (
    <div className="max-w-5xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center gap-4">
        <Button variant="ghost" size="icon" asChild><Link href="/admin/orders"><ArrowLeft className="h-5 w-5" /></Link></Button>
        <div className="flex-1 min-w-0">
          <div className="flex flex-wrap items-center gap-3">
            <h1 className="text-xl sm:text-2xl font-bold text-gray-900 truncate">{order.mOrderId}</h1>
            {getStatusBadge(order.status)}
          </div>
          <p className="text-sm text-gray-500 mt-1">Created {formatDateTime(order.createdAt)}</p>
        </div>
      </div>
      <Separator />

      <Tabs defaultValue="overview" className="w-full">
        <TabsList className="w-full sm:w-auto">
          <TabsTrigger value="overview" className="gap-1.5"><Info className="h-4 w-4 hidden sm:block" /> Overview</TabsTrigger>
          <TabsTrigger value="notify" className="gap-1.5"><Bell className="h-4 w-4 hidden sm:block" /> Notify Logs</TabsTrigger>
          <TabsTrigger value="screenshots" className="gap-1.5"><ImageIcon className="h-4 w-4 hidden sm:block" /> Screenshots ({order.screenshots.length})</TabsTrigger>
          <TabsTrigger value="json" className="gap-1.5"><FileText className="h-4 w-4 hidden sm:block" /> JSON Data</TabsTrigger>
          <TabsTrigger value="logs" className="gap-1.5"><Clock className="h-4 w-4 hidden sm:block" /> Logs ({order.logs.length})</TabsTrigger>
        </TabsList>

        {/* Overview Tab */}
        <TabsContent value="overview" className="mt-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Order Information</CardTitle>
              <CardDescription>Complete details for this order</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-x-8 divide-y lg:divide-y-0 lg:divide-x divide-gray-100">
                <div className="space-y-0">
                  <InfoRow label="Internal Order ID"><span className="text-sm font-mono text-gray-900">{order.id}</span></InfoRow>
                  <InfoRow label="Merchant Order ID"><span className="text-sm font-mono text-gray-900">{order.mOrderId}</span></InfoRow>
                  <InfoRow label="Gateway">
                    <Badge className={
                      order.gateway === 'LGPAY'
                        ? 'bg-blue-100 text-blue-800 hover:bg-blue-100 border-blue-200'
                        : 'bg-emerald-100 text-emerald-800 hover:bg-emerald-100 border-emerald-200'
                    }>
                      {order.gateway === 'LGPAY' ? 'LG-Pay' : 'SilkPay'}
                    </Badge>
                  </InfoRow>
                  <InfoRow label="SilkPay Pay Order ID"><CopyButton text={order.payOrderId} label="Pay Order ID" /></InfoRow>
                  <InfoRow label="Amount"><span className="text-sm font-medium text-gray-900">{order.amount.toLocaleString()} <span className="font-normal text-gray-500">{order.currency}</span></span></InfoRow>
                  <InfoRow label="Paid Amount"><span className="text-sm font-medium text-gray-900">{order.paidAmount.toLocaleString()} <span className="font-normal text-gray-500">{order.currency}</span></span></InfoRow>
                  <InfoRow label="Status">{getStatusBadge(order.status)}</InfoRow>
                  <InfoRow label="UTR"><CopyButton text={order.utr} label="UTR" /></InfoRow>
                  <InfoRow label="Customer Name">
                    {order.customerName ? (
                      <div className="flex items-center gap-1.5"><User className="h-4 w-4 text-gray-400" /><span className="text-sm text-gray-900">{order.customerName}</span></div>
                    ) : <span className="text-gray-400">\u2014</span>}
                  </InfoRow>
                  <InfoRow label="Customer Mobile">
                    {order.customerMobile ? (
                      <div className="flex items-center gap-1.5"><Phone className="h-4 w-4 text-gray-400" /><span className="text-sm text-gray-900">{order.customerMobile}</span></div>
                    ) : <span className="text-gray-400">\u2014</span>}
                  </InfoRow>
                </div>
                <div className="space-y-0 lg:pl-8">
                  <InfoRow label="Payment URL">
                    {order.paymentUrl ? (
                      <div className="flex items-center gap-1.5 flex-wrap">
                        <a href={order.paymentUrl} target="_blank" rel="noopener noreferrer" className="text-sm text-emerald-600 hover:text-emerald-700 hover:underline break-all font-mono">{order.paymentUrl}</a>
                        <Button variant="ghost" size="icon" className="h-7 w-7 shrink-0 text-gray-400 hover:text-gray-600" onClick={async () => { try { await navigator.clipboard.writeText(order.paymentUrl!); toast.success('URL copied'); } catch { toast.error('Failed'); } }}><Copy className="h-3.5 w-3.5" /></Button>
                      </div>
                    ) : <span className="text-gray-400">\u2014</span>}
                  </InfoRow>
                  <InfoRow label="Sign"><CopyButton text={order.sign} label="Sign" /></InfoRow>
                  <InfoRow label="Sign Verified">
                    {order.signVerified
                      ? <div className="flex items-center gap-1.5"><CheckCircle className="h-4 w-4 text-emerald-500" /><span className="text-sm font-medium text-emerald-700">Yes</span></div>
                      : <div className="flex items-center gap-1.5"><XCircle className="h-4 w-4 text-red-500" /><span className="text-sm font-medium text-red-700">No</span></div>}
                  </InfoRow>
                  <InfoRow label="Created At"><span className="text-sm text-gray-900">{formatDateTime(order.createdAt)}</span></InfoRow>
                  <InfoRow label="Callback At"><span className="text-sm text-gray-900">{formatDateTime(order.callbackAt)}</span></InfoRow>
                  <InfoRow label="Telegram Sent">
                    {order.telegramSent
                      ? <div className="flex items-center gap-1.5"><CheckCircle className="h-4 w-4 text-emerald-500" /><span className="text-sm font-medium text-emerald-700">Yes</span></div>
                      : <div className="flex items-center gap-1.5"><XCircle className="h-4 w-4 text-red-500" /><span className="text-sm font-medium text-red-700">No</span></div>}
                  </InfoRow>
                  {order.telegramError && (
                    <InfoRow label="Telegram Error">
                      <div className="flex items-start gap-1.5"><AlertTriangle className="h-4 w-4 text-amber-500 mt-0.5 shrink-0" /><span className="text-sm text-red-600">{order.telegramError}</span></div>
                    </InfoRow>
                  )}
                  <InfoRow label="Screenshots">
                    <span className="text-sm text-gray-900">{order.screenshots.length} file(s)</span>
                  </InfoRow>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Notify Logs Tab */}
        <TabsContent value="notify" className="mt-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Notification Logs</CardTitle>
              <CardDescription>Track all telegram and notification attempts ({order.notifyLogs.length} entries)</CardDescription>
            </CardHeader>
            <CardContent>
              {order.notifyLogs.length === 0 ? (
                <div className="py-8 text-center text-gray-400">
                  <Bell className="h-8 w-8 mx-auto mb-2 opacity-50" />
                  <p className="text-sm">No notifications sent for this order</p>
                </div>
              ) : (
                <div className="space-y-4">
                  {order.notifyLogs.map((nl) => (
                    <div key={nl.id} className="rounded-lg border p-4 space-y-3">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <Bell className="h-4 w-4 text-gray-400" />
                          <span className="text-sm font-medium text-gray-700">{nl.type}</span>
                          {getNotifyStatusBadge(nl.status)}
                        </div>
                        <span className="text-xs text-gray-400">{formatDateTime(nl.createdAt)}</span>
                      </div>
                      {nl.recipient && <p className="text-xs text-gray-500">To: <span className="font-mono">{nl.recipient}</span> · Attempts: {nl.attempts}</p>}
                      <div className="rounded bg-gray-50 p-3 text-xs font-mono text-gray-700 whitespace-pre-wrap break-words max-h-32 overflow-y-auto">{nl.message}</div>
                      {nl.response && (
                        <details className="text-xs">
                          <summary className="cursor-pointer text-gray-500 hover:text-gray-700">Response</summary>
                          <pre className="mt-1 rounded bg-gray-50 p-2 text-gray-600 max-h-32 overflow-y-auto">{nl.response}</pre>
                        </details>
                      )}
                      {nl.error && (
                        <div className="flex items-start gap-1.5 text-xs">
                          <AlertTriangle className="h-3.5 w-3.5 text-red-500 mt-0.5 shrink-0" />
                          <span className="text-red-600">{nl.error}</span>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* Screenshots Tab */}
        <TabsContent value="screenshots" className="mt-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Payment Screenshots</CardTitle>
              <CardDescription>Screenshots uploaded by the customer ({order.screenshots.length} files)</CardDescription>
            </CardHeader>
            <CardContent>
              {order.screenshots.length === 0 ? (
                <div className="py-8 text-center text-gray-400">
                  <ImageIcon className="h-8 w-8 mx-auto mb-2 opacity-50" />
                  <p className="text-sm">No screenshots uploaded for this order</p>
                </div>
              ) : (
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  {order.screenshots.map((ss) => (
                    <div key={ss.id} className="group relative rounded-lg border overflow-hidden">
                      <img
                        src={`/api/payin/screenshot/${ss.id}`}
                        alt={ss.fileName}
                        className="w-full h-48 object-cover cursor-pointer"
                        onClick={() => setExpandedScreenshot(ss.id)}
                      />
                      <div className="p-3 flex items-center justify-between bg-gray-50">
                        <div className="min-w-0 flex-1">
                          <p className="text-xs font-medium text-gray-700 truncate">{ss.fileName}</p>
                          <p className="text-xs text-gray-400">{(ss.fileSize / 1024).toFixed(1)} KB · {formatDateTime(ss.createdAt)}</p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>

          {/* Expanded screenshot modal */}
          {expandedScreenshot && (
            <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4" onClick={() => setExpandedScreenshot(null)}>
              <img
                src={`/api/payin/screenshot/${expandedScreenshot}`}
                alt="Expanded screenshot"
                className="max-w-full max-h-[90vh] object-contain rounded-lg"
                onClick={(e) => e.stopPropagation()}
              />
            </div>
          )}
        </TabsContent>

        {/* JSON Data Tab */}
        <TabsContent value="json" className="mt-6 space-y-4">
          <JsonBlock title="Create Request" data={createRequestData} />
          <JsonBlock title="Callback Payload" data={order.callbackPayload} />
        </TabsContent>

        {/* Logs Tab */}
        <TabsContent value="logs" className="mt-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Order Logs</CardTitle>
              <CardDescription>Timeline of events ({order.logs.length} entries)</CardDescription>
            </CardHeader>
            <CardContent>
              {order.logs.length === 0 ? (
                <div className="py-8 text-center text-gray-400">
                  <Clock className="h-8 w-8 mx-auto mb-2 opacity-50" />
                  <p className="text-sm">No logs recorded</p>
                </div>
              ) : (
                <div className="relative max-h-[500px] overflow-y-auto">
                  <div className="absolute left-[7px] top-2 bottom-2 w-px bg-gray-200" />
                  <div className="space-y-0">
                    {order.logs.map((log) => (
                      <div key={log.id} className="relative flex gap-4 py-3">
                        <div className="relative z-10 mt-1.5 shrink-0">
                          <div className={`w-3.5 h-3.5 rounded-full border-2 ${
                            log.level === 'ERROR' ? 'bg-red-100 border-red-400' :
                            log.level === 'WARN' ? 'bg-amber-100 border-amber-400' :
                            log.level === 'INFO' ? 'bg-blue-100 border-blue-400' :
                            'bg-gray-100 border-gray-400'
                          }`} />
                        </div>
                        <div className="flex-1 min-w-0 flex flex-col sm:flex-row sm:items-start gap-1 sm:gap-3">
                          <span className="text-xs text-gray-400 font-mono shrink-0 sm:w-44 pt-0.5">{formatDateTime(log.createdAt)}</span>
                          <div className="flex items-start gap-2 flex-1">
                            {getLogBadge(log.level)}
                            <span className="text-sm text-gray-700 break-words">{log.message}</span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
