'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  User,
  Wifi,
  CreditCard,
  Receipt,
  Download,
  Upload,
  Clock,
  Activity,
  HelpCircle,
  Plus,
  Mail,
  Phone,
  MapPin,
  Globe,
  Eye,
  Loader2,
  AlertTriangle,
  Shield,
  Zap,
  FileText,
  ArrowUpRight,
  Calendar,
  Monitor,
} from 'lucide-react'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Progress } from '@/components/ui/progress'
import { Separator } from '@/components/ui/separator'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { api } from '@/lib/api'

// ---- Types ----
interface PortalStats {
  users: {
    total: number
    active: number
    expired: number
    suspended: number
    pending: number
  }
  revenue: {
    total: number
    thisMonth: number
    unpaid: number
  }
  subscriptions: {
    total: number
    active: number
  }
  network: {
    onlineOLTs: number
    onus: Record<string, number>
    totalONUs: number
  }
}

// ---- Helpers ----
function formatCurrency(amount: number): string {
  return new Intl.NumberFormat('en-BD', {
    style: 'currency',
    currency: 'BDT',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(amount)
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  })
}

// ---- Mock Data for Portal ----
const mockClientData = {
  name: 'Rahim Uddin',
  email: 'rahim@example.com',
  phone: '+880 1712 345678',
  address: 'House 42, Road 7, Dhanmondi, Dhaka 1205',
  plan: {
    name: 'Fiber 50 Mbps',
    speed: '50 Mbps',
    price: 1200,
  },
  expiryDate: '2025-08-15',
  status: 'ACTIVE',
  ipAddress: '10.10.100.42',
}

const mockInvoices = [
  { id: '1', invoiceNumber: 'INV-2025-042', amount: 1200, status: 'PAID', dueDate: '2025-07-01', paidDate: '2025-06-28' },
  { id: '2', invoiceNumber: 'INV-2025-041', amount: 1200, status: 'PAID', dueDate: '2025-06-01', paidDate: '2025-05-30' },
  { id: '3', invoiceNumber: 'INV-2025-040', amount: 1200, status: 'UNPAID', dueDate: '2025-05-01', paidDate: null },
  { id: '4', invoiceNumber: 'INV-2025-039', amount: 1200, status: 'PAID', dueDate: '2025-04-01', paidDate: '2025-03-29' },
]

const mockPayments = [
  { id: '1', amount: 1200, method: 'bKash', date: '2025-06-28', transactionId: 'TXN827361' },
  { id: '2', amount: 1200, method: 'Nagad', date: '2025-05-30', transactionId: 'TXN719283' },
  { id: '3', amount: 1200, method: 'Cash', date: '2025-03-29', transactionId: 'REC00421' },
]

const mockUsage = {
  download: 45.2,
  upload: 12.8,
  sessions: 28,
  avgDuration: '4h 32m',
}

const mockTickets = [
  { id: '1', subject: 'Internet speed is slow', status: 'OPEN', priority: 'HIGH', date: '2025-06-25' },
  { id: '2', subject: 'Connection drops frequently', status: 'RESOLVED', priority: 'MEDIUM', date: '2025-06-10' },
]

const invoiceStatusColor: Record<string, string> = {
  PAID: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
  UNPAID: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
  DUE: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
  PARTIAL: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400',
}

const ticketStatusColor: Record<string, string> = {
  OPEN: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
  IN_PROGRESS: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
  RESOLVED: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
  CLOSED: 'bg-gray-100 text-gray-600 dark:bg-gray-800/30 dark:text-gray-400',
}

// ---- Skeleton ----
function CardSkeleton() {
  return (
    <Card className="p-4">
      <div className="flex items-center gap-4">
        <Skeleton className="size-10 rounded-lg" />
        <div className="flex-1 space-y-2">
          <Skeleton className="h-4 w-24" />
          <Skeleton className="h-7 w-20" />
        </div>
      </div>
    </Card>
  )
}

// ---- Main Component ----
export default function UserPortalView() {
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [stats, setStats] = useState<PortalStats | null>(null)

  const fetchStats = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const res = await api.get<PortalStats>('/api/dashboard/stats')
      if (res.success && res.data) setStats(res.data)
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Failed to load data'
      setError(message)
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchStats()
  }, [fetchStats])

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center py-20 gap-4">
        <AlertTriangle className="size-12 text-destructive" />
        <p className="text-muted-foreground text-center">{error}</p>
        <Button onClick={fetchStats} variant="outline">
          Retry
        </Button>
      </div>
    )
  }

  return (
    <div className="space-y-6 p-4 md:p-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <div className="flex items-center gap-2">
            <div className="flex items-center justify-center size-10 rounded-full bg-primary text-primary-foreground">
              <User className="size-5" />
            </div>
            <div>
              <h1 className="text-2xl md:text-3xl font-bold tracking-tight">Client Portal Preview</h1>
              <p className="text-muted-foreground mt-0.5">
                Simulated view of what a client would see
              </p>
            </div>
          </div>
        </div>
        <Badge variant="outline" className="w-fit gap-1.5 text-xs">
          <Eye className="size-3" />
          Preview Mode
        </Badge>
      </div>

      {/* Account Status Banner */}
      <Card className="bg-gradient-to-r from-emerald-500 to-teal-600 text-white border-0">
        <CardContent className="p-6">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div className="flex items-center gap-4">
              <div className="flex items-center justify-center size-14 rounded-full bg-white/20 shrink-0">
                <span className="text-xl font-bold">
                  {mockClientData.name.charAt(0)}
                </span>
              </div>
              <div>
                <h2 className="text-lg font-bold">{mockClientData.name}</h2>
                <p className="text-sm text-white/80">{mockClientData.email} &middot; {mockClientData.phone}</p>
                <p className="text-xs text-white/60 mt-0.5">{mockClientData.address}</p>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <Badge className="bg-white/20 text-white hover:bg-white/30 border-0">
                <Shield className="size-3 mr-1" />
                {mockClientData.status}
              </Badge>
              <Badge className="bg-white/20 text-white hover:bg-white/30 border-0">
                <Globe className="size-3 mr-1" />
                {mockClientData.ipAddress}
              </Badge>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Info Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {loading ? (
          Array.from({ length: 4 }).map((_, i) => <CardSkeleton key={i} />)
        ) : (
          <>
            {/* Current Plan */}
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="flex items-center justify-center size-10 rounded-lg bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400">
                  <Zap className="size-5" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs text-muted-foreground font-medium">Current Plan</p>
                  <p className="text-sm font-bold truncate">{mockClientData.plan.name}</p>
                  <p className="text-xs text-muted-foreground">
                    {mockClientData.plan.speed} &middot; {formatCurrency(mockClientData.plan.price)}/mo
                  </p>
                </div>
              </div>
            </Card>

            {/* Expiry Date */}
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="flex items-center justify-center size-10 rounded-lg bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400">
                  <Calendar className="size-5" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs text-muted-foreground font-medium">Expiry Date</p>
                  <p className="text-sm font-bold truncate">{formatDate(mockClientData.expiryDate)}</p>
                  <p className="text-xs text-emerald-600 dark:text-emerald-400">19 days remaining</p>
                </div>
              </div>
            </Card>

            {/* Account Status */}
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="flex items-center justify-center size-10 rounded-lg bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400">
                  <Shield className="size-5" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs text-muted-foreground font-medium">Account Status</p>
                  <Badge
                    variant="secondary"
                    className="bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400 mt-1"
                  >
                    {mockClientData.status}
                  </Badge>
                </div>
              </div>
            </Card>

            {/* IP Address */}
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="flex items-center justify-center size-10 rounded-lg bg-blue-100 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400">
                  <Globe className="size-5" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs text-muted-foreground font-medium">IP Address</p>
                  <p className="text-sm font-bold font-mono truncate">{mockClientData.ipAddress}</p>
                  <p className="text-xs text-muted-foreground">Dynamic IP</p>
                </div>
              </div>
            </Card>
          </>
        )}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Billing History */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="text-base flex items-center gap-2">
                  <Receipt className="size-4" />
                  Billing History
                </CardTitle>
                <CardDescription>Recent invoices and payment status</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="max-h-72 overflow-y-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Invoice #</TableHead>
                    <TableHead className="text-right">Amount</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="hidden sm:table-cell">Due Date</TableHead>
                    <TableHead className="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {mockInvoices.map((inv) => (
                    <TableRow key={inv.id}>
                      <TableCell className="font-mono text-xs">{inv.invoiceNumber}</TableCell>
                      <TableCell className="text-right font-medium">{formatCurrency(inv.amount)}</TableCell>
                      <TableCell>
                        <Badge variant="secondary" className={invoiceStatusColor[inv.status] || ''}>
                          {inv.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="hidden sm:table-cell text-xs text-muted-foreground">
                        {formatDate(inv.dueDate)}
                      </TableCell>
                      <TableCell className="text-right">
                        {inv.status === 'UNPAID' ? (
                          <Button size="sm" variant="default" className="h-7 text-xs gap-1">
                            <CreditCard className="size-3" />
                            Pay
                          </Button>
                        ) : (
                          <Button size="sm" variant="ghost" className="h-7 text-xs gap-1">
                            <Eye className="size-3" />
                            View
                          </Button>
                        )}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>

        {/* Payment History */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="text-base flex items-center gap-2">
                  <CreditCard className="size-4" />
                  Payment History
                </CardTitle>
                <CardDescription>Recent successful payments</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="max-h-72 overflow-y-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Amount</TableHead>
                    <TableHead>Method</TableHead>
                    <TableHead className="hidden sm:table-cell">Date</TableHead>
                    <TableHead className="hidden md:table-cell">Transaction ID</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {mockPayments.map((pay) => (
                    <TableRow key={pay.id}>
                      <TableCell className="font-medium">{formatCurrency(pay.amount)}</TableCell>
                      <TableCell>
                        <Badge variant="outline">{pay.method}</Badge>
                      </TableCell>
                      <TableCell className="hidden sm:table-cell text-xs text-muted-foreground">
                        {formatDate(pay.date)}
                      </TableCell>
                      <TableCell className="hidden md:table-cell text-xs text-muted-foreground font-mono">
                        {pay.transactionId}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Usage Statistics */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="text-base flex items-center gap-2">
                <Activity className="size-4" />
                Usage Statistics
              </CardTitle>
              <CardDescription>This month&apos;s data usage and session info</CardDescription>
            </div>
            <Badge variant="secondary" className="flex items-center gap-1">
              <Monitor className="size-3" />
              This Month
            </Badge>
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            {/* Download */}
            <div className="space-y-2">
              <div className="flex items-center gap-2 text-sm">
                <Download className="size-4 text-emerald-500" />
                <span className="font-medium">Download</span>
              </div>
              <p className="text-2xl font-bold">{mockUsage.download} GB</p>
              <Progress value={60} className="h-2" />
              <p className="text-xs text-muted-foreground">60% of 75 GB limit</p>
            </div>

            {/* Upload */}
            <div className="space-y-2">
              <div className="flex items-center gap-2 text-sm">
                <Upload className="size-4 text-blue-500" />
                <span className="font-medium">Upload</span>
              </div>
              <p className="text-2xl font-bold">{mockUsage.upload} GB</p>
              <Progress value={40} className="h-2" />
              <p className="text-xs text-muted-foreground">40% of 30 GB limit</p>
            </div>

            {/* Sessions */}
            <div className="space-y-2">
              <div className="flex items-center gap-2 text-sm">
                <Wifi className="size-4 text-violet-500" />
                <span className="font-medium">Sessions</span>
              </div>
              <p className="text-2xl font-bold">{mockUsage.sessions}</p>
              <p className="text-xs text-muted-foreground">Active connections this month</p>
            </div>

            {/* Avg Duration */}
            <div className="space-y-2">
              <div className="flex items-center gap-2 text-sm">
                <Clock className="size-4 text-amber-500" />
                <span className="font-medium">Avg Duration</span>
              </div>
              <p className="text-2xl font-bold">{mockUsage.avgDuration}</p>
              <p className="text-xs text-muted-foreground">Average session length</p>
            </div>
          </div>
        </CardContent>
      </Card>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Support Section */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="text-base flex items-center gap-2">
                  <HelpCircle className="size-4" />
                  Support
                </CardTitle>
                <CardDescription>Submit and track support tickets</CardDescription>
              </div>
              <Button size="sm" className="gap-1.5">
                <Plus className="size-3.5" />
                Submit Ticket
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            {mockTickets.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
                <HelpCircle className="size-8 opacity-50 mb-2" />
                <p className="text-sm">No tickets yet</p>
              </div>
            ) : (
              <div className="space-y-3">
                {mockTickets.map((ticket) => (
                  <div
                    key={ticket.id}
                    className="flex items-center justify-between p-3 rounded-lg border hover:bg-muted/50 transition-colors"
                  >
                    <div className="min-w-0 flex-1">
                      <p className="text-sm font-medium truncate">{ticket.subject}</p>
                      <div className="flex items-center gap-2 mt-1">
                        <Badge variant="secondary" className={ticketStatusColor[ticket.status] || ''}>
                          {ticket.status}
                        </Badge>
                        <Badge variant="outline" className="text-xs">
                          {ticket.priority}
                        </Badge>
                        <span className="text-xs text-muted-foreground">{formatDate(ticket.date)}</span>
                      </div>
                    </div>
                    <Button variant="ghost" size="sm" className="shrink-0">
                      <ArrowUpRight className="size-4" />
                    </Button>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Account Info */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base flex items-center gap-2">
              <User className="size-4" />
              Account Information
            </CardTitle>
            <CardDescription>Your personal and connection details</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="flex items-center gap-3">
                  <Mail className="size-4 text-muted-foreground shrink-0" />
                  <div className="min-w-0">
                    <p className="text-xs text-muted-foreground">Email</p>
                    <p className="text-sm truncate">{mockClientData.email}</p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <Phone className="size-4 text-muted-foreground shrink-0" />
                  <div className="min-w-0">
                    <p className="text-xs text-muted-foreground">Phone</p>
                    <p className="text-sm truncate">{mockClientData.phone}</p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <MapPin className="size-4 text-muted-foreground shrink-0" />
                  <div className="min-w-0">
                    <p className="text-xs text-muted-foreground">Address</p>
                    <p className="text-sm truncate">{mockClientData.address}</p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <Globe className="size-4 text-muted-foreground shrink-0" />
                  <div className="min-w-0">
                    <p className="text-xs text-muted-foreground">IP Address</p>
                    <p className="text-sm font-mono truncate">{mockClientData.ipAddress}</p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <Zap className="size-4 text-muted-foreground shrink-0" />
                  <div className="min-w-0">
                    <p className="text-xs text-muted-foreground">Current Plan</p>
                    <p className="text-sm font-medium truncate">{mockClientData.plan.name}</p>
                    <p className="text-xs text-muted-foreground">
                      {mockClientData.plan.speed} &middot; {formatCurrency(mockClientData.plan.price)}/mo
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <Calendar className="size-4 text-muted-foreground shrink-0" />
                  <div className="min-w-0">
                    <p className="text-xs text-muted-foreground">Expiry Date</p>
                    <p className="text-sm font-medium truncate">{formatDate(mockClientData.expiryDate)}</p>
                  </div>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
