import { useState } from 'react'
import { Card } from '@/components/ui/Card'
import {
  Table,
  TableHead,
  TableBody,
  TableRow,
  TableHeader,
  TableCell,
} from '@/components/ui/Table'
import { Badge } from '@/components/ui/Badge'
import { Button } from '@/components/ui/Button'
import { formatRelativeTime } from '@/lib/utils'
import {
  HeadphonesIcon,
  Clock,
  CheckCircle2,
  AlertCircle,
  Plus,
  Search,
  Filter,
  MoreHorizontal,
} from 'lucide-react'

const tickets = [
  { id: 'SUP-2024-001', subject: 'Login issues after password reset', customer: 'Acme Corp', priority: 'high' as const, status: 'open' as const, assigned: 'Johan Berg', created: new Date(Date.now() - 1000 * 60 * 30).toISOString() },
  { id: 'SUP-2024-002', subject: 'API rate limit questions', customer: 'Nordic Solutions', priority: 'medium' as const, status: 'in_progress' as const, assigned: 'Johan Berg', created: new Date(Date.now() - 1000 * 60 * 120).toISOString() },
  { id: 'SUP-2024-003', subject: 'Feature request: bulk export', customer: 'TechStart AB', priority: 'low' as const, status: 'open' as const, assigned: 'Unassigned', created: new Date(Date.now() - 1000 * 60 * 60 * 4).toISOString() },
  { id: 'SUP-2024-004', subject: 'Billing discrepancy on invoice #89', customer: 'Global Industries', priority: 'high' as const, status: 'in_progress' as const, assigned: 'Elena Rossi', created: new Date(Date.now() - 1000 * 60 * 60 * 6).toISOString() },
  { id: 'SUP-2024-005', subject: 'Integration documentation outdated', customer: 'ScandiTech', priority: 'medium' as const, status: 'resolved' as const, assigned: 'Johan Berg', created: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString() },
  { id: 'SUP-2024-006', subject: 'Mobile app crash on iOS', customer: 'MegaCorp', priority: 'high' as const, status: 'open' as const, assigned: 'Unassigned', created: new Date(Date.now() - 1000 * 60 * 60 * 2).toISOString() },
]

const tabs = ['All', 'Open', 'In Progress', 'Resolved']

export function SupportPage() {
  const [activeTab, setActiveTab] = useState('All')
  const [searchQuery, setSearchQuery] = useState('')

  const openCount = tickets.filter((t) => t.status === 'open').length
  const inProgressCount = tickets.filter((t) => t.status === 'in_progress').length
  const resolvedCount = tickets.filter((t) => t.status === 'resolved').length
  const _avgResponseTime = '2.4h'
  void _avgResponseTime

  const filteredTickets = tickets.filter((t) => {
    const matchesSearch =
      t.subject.toLowerCase().includes(searchQuery.toLowerCase()) ||
      t.customer.toLowerCase().includes(searchQuery.toLowerCase()) ||
      t.id.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesTab = activeTab === 'All' || t.status === activeTab.toLowerCase().replace(' ', '_')
    return matchesSearch && matchesTab
  })

  return (
    <div className="space-y-8">
      {/* Page Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-xl font-semibold text-text-primary">Support</h1>
          <p className="text-sm text-text-secondary mt-0.5">Customer support tickets</p>
        </div>
        <Button icon={<Plus size={16} />}>New Ticket</Button>
      </div>

      {/* Quick Stats */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-5">
        <Card padding="md">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-primary-light flex items-center justify-center text-primary">
              <HeadphonesIcon size={18} />
            </div>
            <div>
              <p className="text-2xl font-semibold text-text-primary">{tickets.length}</p>
              <p className="text-xs text-text-secondary">Total Tickets</p>
            </div>
          </div>
        </Card>
        <Card padding="md">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-warning-light flex items-center justify-center text-warning">
              <AlertCircle size={18} />
            </div>
            <div>
              <p className="text-2xl font-semibold text-text-primary">{openCount}</p>
              <p className="text-xs text-text-secondary">Open</p>
            </div>
          </div>
        </Card>
        <Card padding="md">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-primary-light flex items-center justify-center text-primary">
              <Clock size={18} />
            </div>
            <div>
              <p className="text-2xl font-semibold text-text-primary">{inProgressCount}</p>
              <p className="text-xs text-text-secondary">In Progress</p>
            </div>
          </div>
        </Card>
        <Card padding="md">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-success-light flex items-center justify-center text-success">
              <CheckCircle2 size={18} />
            </div>
            <div>
              <p className="text-2xl font-semibold text-text-primary">{resolvedCount}</p>
              <p className="text-xs text-text-secondary">Resolved</p>
            </div>
          </div>
        </Card>
      </div>

      {/* Tabs + Search */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
        <div className="flex items-center gap-1 bg-bg rounded-xl p-1">
          {tabs.map((tab) => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
                activeTab === tab
                  ? 'bg-surface text-text-primary shadow-sm'
                  : 'text-text-secondary hover:text-text-primary'
              }`}
            >
              {tab}
            </button>
          ))}
        </div>
        <div className="flex items-center gap-2 w-full sm:w-auto">
          <div className="relative flex-1 sm:flex-initial">
            <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-secondary" />
            <input
              type="text"
              placeholder="Search tickets..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full sm:w-64 h-10 pl-9 pr-4 rounded-[14px] border bg-surface text-sm text-text-primary placeholder:text-text-secondary/50 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary/30"
            />
          </div>
          <Button variant="secondary" size="sm" icon={<Filter size={14} />}>
            Filter
          </Button>
        </div>
      </div>

      {/* Tickets Table */}
      <Card>
        <Table>
          <TableHead>
            <TableRow>
              <TableHeader>Ticket</TableHeader>
              <TableHeader>Subject</TableHeader>
              <TableHeader>Customer</TableHeader>
              <TableHeader>Priority</TableHeader>
              <TableHeader>Status</TableHeader>
              <TableHeader>Assigned</TableHeader>
              <TableHeader>Created</TableHeader>
              <TableHeader align="right"></TableHeader>
            </TableRow>
          </TableHead>
          <TableBody>
            {filteredTickets.map((ticket) => (
              <TableRow key={ticket.id}>
                <TableCell>
                  <span className="font-medium text-sm">{ticket.id}</span>
                </TableCell>
                <TableCell>
                  <span className="text-sm text-text-primary">{ticket.subject}</span>
                </TableCell>
                <TableCell>{ticket.customer}</TableCell>
                <TableCell>
                  <Badge
                    variant={
                      ticket.priority === 'high'
                        ? 'danger'
                        : ticket.priority === 'medium'
                        ? 'warning'
                        : 'default'
                    }
                    size="sm"
                  >
                    {ticket.priority}
                  </Badge>
                </TableCell>
                <TableCell>
                  <Badge
                    variant={
                      ticket.status === 'resolved'
                        ? 'success'
                        : ticket.status === 'in_progress'
                        ? 'primary'
                        : 'warning'
                    }
                    size="sm"
                  >
                    {ticket.status.replace('_', ' ')}
                  </Badge>
                </TableCell>
                <TableCell>{ticket.assigned}</TableCell>
                <TableCell>
                  <span className="text-xs text-text-secondary">{formatRelativeTime(ticket.created)}</span>
                </TableCell>
                <TableCell align="right">
                  <button className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-bg text-text-secondary">
                    <MoreHorizontal size={16} />
                  </button>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </Card>
    </div>
  )
}
