'use client';

import { useCallback, useEffect, useState } from 'react';
import {
  apiListBroadcasts,
  apiDeleteBroadcast,
  apiSendBroadcast,
  apiPauseBroadcast,
  apiCloneBroadcast,
  type ApiBroadcast,
} from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Badge } from '@/components/ui/badge';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { MoreHorizontal, Plus, Send, Pause, Copy, Trash2, BarChart3 } from 'lucide-react';
import Link from 'next/link';
import { useToast } from '@/components/ui/toast';

const statusColors: Record<ApiBroadcast['status'], string> = {
  draft: 'bg-gray-500',
  scheduled: 'bg-blue-500',
  sending: 'bg-yellow-500',
  sent: 'bg-green-500',
  paused: 'bg-orange-500',
};

export default function BroadcastsPage() {
  const [broadcasts, setBroadcasts] = useState<ApiBroadcast[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState('');
  const [deleteDialog, setDeleteDialog] = useState<ApiBroadcast | null>(null);
  const { toast } = useToast();

  const loadBroadcasts = useCallback(async () => {
    try {
      setLoading(true);
      const { data, error } = await apiListBroadcasts();
      if (error) throw new Error(error);
      setBroadcasts(data?.broadcasts ?? []);
    } catch (err) {
      toast({
        title: 'Error',
        description: err instanceof Error ? err.message : 'Failed to load broadcasts',
        variant: 'error',
      });
    } finally {
      setLoading(false);
    }
  }, [toast]);

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

  async function handleDelete(broadcast: ApiBroadcast) {
    try {
      const { error } = await apiDeleteBroadcast(broadcast.id);
      if (error) throw new Error(error);
      toast({ title: 'Success', description: 'Broadcast deleted', variant: 'success' });
      loadBroadcasts();
    } catch (err) {
      toast({
        title: 'Error',
        description: err instanceof Error ? err.message : 'Failed to delete',
        variant: 'error',
      });
    }
    setDeleteDialog(null);
  }

  async function handleSend(id: string) {
    try {
      const { error } = await apiSendBroadcast(id);
      if (error) throw new Error(error);
      toast({ title: 'Success', description: 'Broadcast sending started', variant: 'success' });
      loadBroadcasts();
    } catch (err) {
      toast({
        title: 'Error',
        description: err instanceof Error ? err.message : 'Failed to send',
        variant: 'error',
      });
    }
  }

  async function handlePause(id: string) {
    try {
      const { error } = await apiPauseBroadcast(id);
      if (error) throw new Error(error);
      toast({ title: 'Success', description: 'Broadcast paused', variant: 'success' });
      loadBroadcasts();
    } catch (err) {
      toast({
        title: 'Error',
        description: err instanceof Error ? err.message : 'Failed to pause',
        variant: 'error',
      });
    }
  }

  async function handleClone(broadcast: ApiBroadcast, variant?: 'control' | 'treatment') {
    try {
      const { error } = await apiCloneBroadcast(broadcast.id, variant);
      if (error) throw new Error(error);
      toast({ title: 'Success', description: 'Broadcast cloned', variant: 'success' });
      loadBroadcasts();
    } catch (err) {
      toast({
        title: 'Error',
        description: err instanceof Error ? err.message : 'Failed to clone',
        variant: 'error',
      });
    }
  }

  const filteredBroadcasts = broadcasts.filter(
    b =>
      b.title.toLowerCase().includes(filter.toLowerCase()) ||
      b.body.toLowerCase().includes(filter.toLowerCase())
  );

  if (loading) {
    return (
      <div className="container mx-auto py-8">
        <div className="animate-pulse space-y-4">
          <div className="h-8 w-48 bg-muted rounded" />
          <div className="h-64 bg-muted rounded" />
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-8 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Broadcasts</h1>
          <p className="text-muted-foreground">
            Manage targeted messaging campaigns across all channels
          </p>
        </div>
        <Link href="/broadcasts/new">
          <Button>
            <Plus className="mr-2 h-4 w-4" />
            New Broadcast
          </Button>
        </Link>
      </div>

      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>All Broadcasts</CardTitle>
              <CardDescription>{broadcasts.length} total broadcasts</CardDescription>
            </div>
            <Input
              placeholder="Filter broadcasts..."
              value={filter}
              onChange={e => setFilter(e.target.value)}
              className="w-64"
            />
          </div>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Title</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Channels</TableHead>
                <TableHead>Target</TableHead>
                <TableHead>Metrics</TableHead>
                <TableHead>Created</TableHead>
                <TableHead className="w-12" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredBroadcasts.map(broadcast => (
                <TableRow key={broadcast.id}>
                  <TableCell>
                    <div className="font-medium">{broadcast.title}</div>
                    <div className="text-sm text-muted-foreground line-clamp-1">
                      {broadcast.body}
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge className={statusColors[broadcast.status]}>{broadcast.status}</Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      {broadcast.channels.map(ch => (
                        <Badge key={ch} variant="outline">
                          {ch}
                        </Badge>
                      ))}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="text-sm">
                      {broadcast.target.platforms?.join(', ') || 'All platforms'}
                    </div>
                    {broadcast.target.percentageRollout && (
                      <div className="text-xs text-muted-foreground">
                        {broadcast.target.percentageRollout}% rollout
                      </div>
                    )}
                  </TableCell>
                  <TableCell>
                    <div className="text-sm space-y-1">
                      <div>Sent: {broadcast.metrics.sentCount}</div>
                      <div className="text-muted-foreground">
                        Opened: {broadcast.metrics.openedCount} | Clicked:{' '}
                        {broadcast.metrics.clickedCount}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>{new Date(broadcast.createdAt).toLocaleDateString()}</TableCell>
                  <TableCell>
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="icon">
                          <MoreHorizontal className="h-4 w-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem asChild>
                          <Link href={`/broadcasts/${broadcast.id}`}>Edit</Link>
                        </DropdownMenuItem>
                        <DropdownMenuItem asChild>
                          <Link href={`/broadcasts/${broadcast.id}/metrics`}>
                            <BarChart3 className="mr-2 h-4 w-4" />
                            View Metrics
                          </Link>
                        </DropdownMenuItem>
                        {broadcast.status === 'draft' && (
                          <DropdownMenuItem onClick={() => handleSend(broadcast.id)}>
                            <Send className="mr-2 h-4 w-4" />
                            Send Now
                          </DropdownMenuItem>
                        )}
                        {broadcast.status === 'sending' && (
                          <DropdownMenuItem onClick={() => handlePause(broadcast.id)}>
                            <Pause className="mr-2 h-4 w-4" />
                            Pause
                          </DropdownMenuItem>
                        )}
                        <DropdownMenuItem onClick={() => handleClone(broadcast, 'treatment')}>
                          <Copy className="mr-2 h-4 w-4" />
                          Clone (A/B Test)
                        </DropdownMenuItem>
                        <DropdownMenuItem
                          className="text-destructive"
                          onClick={() => setDeleteDialog(broadcast)}
                        >
                          <Trash2 className="mr-2 h-4 w-4" />
                          Delete
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))}
              {filteredBroadcasts.length === 0 && (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                    {filter ? 'No broadcasts match your filter' : 'No broadcasts yet'}
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Dialog open={!!deleteDialog} onOpenChange={() => setDeleteDialog(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete Broadcast</DialogTitle>
            <DialogDescription>
              Are you sure you want to delete &quot;{deleteDialog?.title}&quot;? This action cannot
              be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteDialog(null)}>
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={() => deleteDialog && handleDelete(deleteDialog)}
            >
              Delete
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
