'use client';

import { createProxyFetch } from '@/lib/proxy-fetch';

import { useState, useEffect, useCallback } from 'react';
import { Mail } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';

interface DeliveryEntry {
  id: string;
  pk: string;
  template: string;
  recipient: string;
  channel: string;
  status: string;
  provider?: string;
  attempt: number;
  error?: string;
  createdAt: string;
}

const statusConfig: Record<string, { color: string }> = {
  delivered: { color: 'bg-emerald-50 text-emerald-700' },
  failed: { color: 'bg-red-50 text-red-700' },
  pending: { color: 'bg-amber-50 text-amber-700' },
  retrying: { color: 'bg-blue-50 text-blue-700' },
};

function formatDate(iso: string) {
  return new Date(iso).toLocaleString('en-US', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

const apiFetch = createProxyFetch('/api/delivery');

export default function DeliveryPage() {
  const [entries, setEntries] = useState<DeliveryEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState('all');

  const loadData = useCallback(async () => {
    setLoading(true);
    const params = new URLSearchParams();
    if (statusFilter !== 'all') params.set('status', statusFilter);
    const qs = params.toString() ? `?${params.toString()}` : '';
    const data = await apiFetch(`logs${qs}`);
    setEntries(Array.isArray(data?.entries) ? data.entries : Array.isArray(data) ? data : []);
    setLoading(false);
  }, [statusFilter]);

  useEffect(() => {
    void loadData();
  }, [loadData]);

  async function handleRetry(entry: DeliveryEntry) {
    await apiFetch(`logs/${entry.id}/retry?pk=${encodeURIComponent(entry.pk)}`, {
      method: 'POST',
    });
    loadData();
  }

  const deliveredCount = entries.filter(e => e.status === 'delivered').length;
  const failedCount = entries.filter(e => e.status === 'failed').length;
  const rate = entries.length > 0 ? Math.round((deliveredCount / entries.length) * 100) : 0;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Email Delivery Log</h1>
          <p className="text-sm text-muted-foreground">
            Monitor transactional email delivery, retry failures
          </p>
        </div>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Total Sent</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{entries.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Delivered</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-emerald-600">{deliveredCount}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Failed</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-600">{failedCount}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Success Rate
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{rate}%</div>
          </CardContent>
        </Card>
      </div>

      <div className="flex items-center gap-4">
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Filter status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All</SelectItem>
            <SelectItem value="delivered">Delivered</SelectItem>
            <SelectItem value="failed">Failed</SelectItem>
            <SelectItem value="pending">Pending</SelectItem>
            <SelectItem value="retrying">Retrying</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <Card>
        <CardContent className="p-0">
          {loading ? (
            <div className="p-8 text-center text-muted-foreground">Loading...</div>
          ) : entries.length === 0 ? (
            <div className="p-8 text-center text-muted-foreground">
              <Mail className="mx-auto mb-2 h-8 w-8 opacity-40" />
              No delivery entries found.
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Template</TableHead>
                  <TableHead>Recipient</TableHead>
                  <TableHead>Channel</TableHead>
                  <TableHead>Provider</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Attempt</TableHead>
                  <TableHead>Sent</TableHead>
                  <TableHead className="w-[40px]" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {entries.map(e => {
                  const cfg = statusConfig[e.status] || statusConfig.pending;
                  return (
                    <TableRow key={e.id}>
                      <TableCell className="font-medium text-sm">{e.template}</TableCell>
                      <TableCell className="text-sm">{e.recipient}</TableCell>
                      <TableCell>
                        <Badge variant="outline" className="text-xs capitalize">
                          {e.channel}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {e.provider || '—'}
                      </TableCell>
                      <TableCell>
                        <Badge className={`${cfg.color} border-0`}>{e.status}</Badge>
                      </TableCell>
                      <TableCell className="text-xs">{e.attempt}</TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {formatDate(e.createdAt)}
                      </TableCell>
                      <TableCell>
                        {e.status === 'failed' && (
                          <button
                            onClick={() => handleRetry(e)}
                            className="text-xs text-blue-600 hover:underline"
                          >
                            Retry
                          </button>
                        )}
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
