'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Download, Eye, RefreshCw, CheckCircle } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import Badge from '@/components/ui/Badge';
import ActionButton from '@/components/ui/ActionButton';
import { ticketsApi } from '@/lib/api';
import { formatDateTime } from '@/lib/utils';

export default function TicketsPage() {
  const [filters, setFilters] = useState({ search: '', status: '' });
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ['tickets', filters],
    queryFn: () => ticketsApi.getAll(filters),
  });

  const regenerateMutation = useMutation({
    mutationFn: ticketsApi.regenerate,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['tickets'] });
      alert('Ticket regenerated successfully');
    },
  });

  const validateMutation = useMutation({
    mutationFn: ({ ticketId, data }: any) => ticketsApi.validate(ticketId, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['tickets'] });
      alert('Ticket validated successfully');
    },
  });

  const handleRegenerate = async (ticket: any) => {
    if (confirm(`Regenerate ticket ${ticket.ticketNumber}?`)) {
      await regenerateMutation.mutateAsync(ticket.id);
    }
  };

  const handleValidate = async (ticket: any) => {
    await validateMutation.mutateAsync({
      ticketId: ticket.id,
      data: { validatedAt: new Date().toISOString() },
    });
  };

  const columns = [
    {
      key: 'ticketNumber',
      label: 'Ticket Number',
      sortable: true,
      render: (ticket: any) => (
        <span className="font-mono font-semibold">{ticket.ticketNumber || 'N/A'}</span>
      ),
    },
    {
      key: 'booking',
      label: 'Booking',
      render: (ticket: any) => (
        <div>
          <div className="font-medium">{ticket.booking?.bookingRef || 'N/A'}</div>
          <div className="text-sm text-muted-foreground">
            {ticket.booking?.passenger?.fullName || ticket.booking?.contactEmail || 'N/A'}
          </div>
        </div>
      ),
    },
    {
      key: 'trip',
      label: 'Trip',
      render: (ticket: any) => (
        <div>
          <div className="font-medium">
            {ticket.schedule?.originStation?.name || 'N/A'} → {ticket.schedule?.destinationStation?.name || 'N/A'}
          </div>
          <div className="text-sm text-muted-foreground">
            {ticket.schedule?.departureAt ? formatDateTime(ticket.schedule.departureAt) : 'N/A'}
          </div>
        </div>
      ),
    },
    {
      key: 'seat',
      label: 'Seat',
      render: (ticket: any) => (
        <span className="font-mono">{ticket.seat?.seatNumber || 'N/A'}</span>
      ),
    },
    {
      key: 'status',
      label: 'Status',
      render: (ticket: any) => (
        <Badge variant="status" status={ticket.status || 'PENDING'}>
          {ticket.status || 'PENDING'}
        </Badge>
      ),
    },
    {
      key: 'validated',
      label: 'Validated',
      render: (ticket: any) => (
        ticket.validatedAt ? (
          <div className="flex items-center gap-1 text-green-600 dark:text-green-400">
            <CheckCircle className="h-4 w-4" />
            <span className="text-sm">{formatDateTime(ticket.validatedAt)}</span>
          </div>
        ) : (
          <span className="text-sm text-muted-foreground">Not validated</span>
        )
      ),
    },
    {
      key: 'createdAt',
      label: 'Created',
      sortable: true,
      render: (ticket: any) => formatDateTime(ticket.createdAt),
    },
  ];

  const actions = [
    // TODO: Create ticket detail page
    // {
    //   label: 'View Details',
    //   onClick: (ticket: any) => window.location.href = `/tickets/${ticket.id}`,
    //   variant: 'secondary' as const,
    //   icon: Eye,
    // },
    {
      label: 'Validate',
      onClick: handleValidate,
      variant: 'primary' as const,
      icon: CheckCircle,
      show: (ticket: any) => !ticket.validatedAt,
    },
    {
      label: 'Regenerate',
      onClick: handleRegenerate,
      variant: 'secondary' as const,
      icon: RefreshCw,
    },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Tickets</h1>
          <p className="text-muted-foreground">Manage tickets and validations</p>
        </div>
        <ActionButton icon={Download} variant="secondary">Export</ActionButton>
      </div>

      {/* Filters */}
      <div className="card">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="label">Search</label>
            <input
              type="text"
              placeholder="Search by ticket number or booking ref..."
              className="input"
              value={filters.search}
              onChange={(e) => setFilters({ ...filters, search: e.target.value })}
            />
          </div>
          <div>
            <label className="label">Status</label>
            <select
              className="input"
              value={filters.status}
              onChange={(e) => setFilters({ ...filters, status: e.target.value })}
            >
              <option value="">All Status</option>
              <option value="ACTIVE">Active</option>
              <option value="USED">Used</option>
              <option value="CANCELLED">Cancelled</option>
              <option value="EXPIRED">Expired</option>
            </select>
          </div>
        </div>
      </div>

      {/* Tickets Table */}
      <DataTable
        data={data?.items || []}
        columns={columns}
        actions={actions}
        loading={isLoading}
        emptyMessage="No tickets found"
      />
    </div>
  );
}
