'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Megaphone, Trash2, Search, Plus, Edit, ChevronLeft, ChevronRight } from 'lucide-react';
import { toast } from 'sonner';

import { promotionsApi, type Promotion } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table';
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select';

export default function PromotionsPage() {
  const queryClient = useQueryClient();
  const [params, setParams] = useState({ page: 1, per_page: 20, search: '' });
  const [search, setSearch] = useState('');
  const [editingPromotion, setEditingPromotion] = useState<Promotion | null>(null);
  const [isCreating, setIsCreating] = useState(false);
  const [formData, setFormData] = useState({
    promotion_id: '',
    title: '',
    message: '',
    link: '',
    start_date: '',
    end_date: '',
    target_tier: 'free' as 'free' | 'pro',
    is_active: true,
  });

  const { data, isLoading } = useQuery({
    queryKey: ['promotions', params],
    queryFn: () => promotionsApi.list(params),
  });

  const createMutation = useMutation({
    mutationFn: promotionsApi.create,
    onSuccess: () => {
      toast.success('Promotion created');
      queryClient.invalidateQueries({ queryKey: ['promotions'] });
      setIsCreating(false);
      resetForm();
    },
    onError: () => toast.error('Failed to create promotion'),
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: any }) => promotionsApi.update(id, data),
    onSuccess: () => {
      toast.success('Promotion updated');
      queryClient.invalidateQueries({ queryKey: ['promotions'] });
      setEditingPromotion(null);
      resetForm();
    },
    onError: () => toast.error('Failed to update promotion'),
  });

  const deleteMutation = useMutation({
    mutationFn: promotionsApi.delete,
    onSuccess: () => {
      toast.success('Promotion deleted');
      queryClient.invalidateQueries({ queryKey: ['promotions'] });
    },
    onError: () => toast.error('Failed to delete promotion'),
  });

  const resetForm = () => {
    setFormData({
      promotion_id: '', title: '', message: '', link: '',
      start_date: '', end_date: '', target_tier: 'free', is_active: true,
    });
  };

  const handleEdit = (promo: Promotion) => {
    setEditingPromotion(promo);
    setFormData({
      promotion_id: promo.promotion_id,
      title: promo.title,
      message: promo.message,
      link: promo.link || '',
      start_date: promo.start_date.split('T')[0],
      end_date: promo.end_date.split('T')[0],
      target_tier: promo.target_tier,
      is_active: promo.is_active,
    });
  };

  const handleSubmit = () => {
    const submitData = {
      ...formData,
      link: formData.link || undefined,
    };
    if (editingPromotion) {
      updateMutation.mutate({ id: editingPromotion.id, data: submitData });
    } else {
      createMutation.mutate(submitData);
    }
  };

  const isActive = (promo: Promotion) => {
    const now = new Date();
    return promo.is_active && new Date(promo.start_date) <= now && new Date(promo.end_date) >= now;
  };

  const totalPages = data ? Math.ceil(data.total / params.per_page) : 0;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Promotions</h1>
          <p className="text-muted-foreground">Manage promotional content and banners</p>
        </div>
        <Button onClick={() => { setIsCreating(true); resetForm(); }}>
          <Plus className="mr-2 h-4 w-4" />
          Add Promotion
        </Button>
      </div>

      <form onSubmit={(e) => { e.preventDefault(); setParams({ ...params, search, page: 1 }); }} className="flex gap-2 max-w-md">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input placeholder="Search..." value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9" />
        </div>
        <Button type="submit" variant="secondary">Search</Button>
      </form>

      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>ID (DB)</TableHead>
              <TableHead>Promotion ID</TableHead>
              <TableHead>Title</TableHead>
              <TableHead>Target</TableHead>
              <TableHead>Date Range</TableHead>
              <TableHead>Status</TableHead>
              <TableHead>Created</TableHead>
              <TableHead className="w-24">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {isLoading ? (
              <TableRow><TableCell colSpan={6} className="text-center py-8">Loading...</TableCell></TableRow>
            ) : data?.data?.length === 0 ? (
              <TableRow><TableCell colSpan={6} className="text-center py-8">No promotions found</TableCell></TableRow>
            ) : (
              data?.data?.map((promo) => (
                <TableRow key={promo.id}>
                  <TableCell className="font-mono text-sm text-muted-foreground">{promo.id}</TableCell>
                  <TableCell><code className="text-xs bg-muted px-2 py-1 rounded">{promo.promotion_id}</code></TableCell>
                  <TableCell className="font-medium">{promo.title}</TableCell>
                  <TableCell>
                    <Badge variant={promo.target_tier === 'pro' ? 'default' : 'secondary'}>
                      {promo.target_tier === 'pro' ? 'Pro Users' : 'Free Users'}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-sm">
                    {new Date(promo.start_date).toLocaleDateString()} - {new Date(promo.end_date).toLocaleDateString()}
                  </TableCell>
                  <TableCell>
                    {isActive(promo) ? (
                      <Badge variant="default" className="bg-green-600">Active</Badge>
                    ) : promo.is_active ? (
                      <Badge variant="secondary">Scheduled</Badge>
                    ) : (
                      <Badge variant="destructive">Inactive</Badge>
                    )}
                  </TableCell>
                  <TableCell>
                    {new Date(promo.created_at).toLocaleDateString()}
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      <Button variant="ghost" size="icon" onClick={() => handleEdit(promo)}>
                        <Edit className="h-4 w-4" />
                      </Button>
                      <AlertDialog>
                        <AlertDialogTrigger asChild>
                          <Button variant="ghost" size="icon" className="text-red-600 hover:text-red-700">
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </AlertDialogTrigger>
                        <AlertDialogContent>
                          <AlertDialogHeader>
                            <AlertDialogTitle>Delete Promotion?</AlertDialogTitle>
                            <AlertDialogDescription>This will permanently delete this promotion.</AlertDialogDescription>
                          </AlertDialogHeader>
                          <AlertDialogFooter>
                            <AlertDialogCancel>Cancel</AlertDialogCancel>
                            <AlertDialogAction onClick={() => deleteMutation.mutate(promo.id)} className="bg-destructive">Delete</AlertDialogAction>
                          </AlertDialogFooter>
                        </AlertDialogContent>
                      </AlertDialog>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {data && totalPages > 1 && (
        <div className="flex items-center justify-between">
          <div className="text-sm text-muted-foreground">Page {params.page} of {totalPages}</div>
          <div className="flex gap-2">
            <Button variant="outline" size="sm" disabled={params.page <= 1} onClick={() => setParams({ ...params, page: params.page - 1 })}>
              <ChevronLeft className="h-4 w-4" /> Previous
            </Button>
            <Button variant="outline" size="sm" disabled={params.page >= totalPages} onClick={() => setParams({ ...params, page: params.page + 1 })}>
              Next <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      {/* Create/Edit Dialog */}
      <Dialog open={isCreating || !!editingPromotion} onOpenChange={(open) => { if (!open) { setIsCreating(false); setEditingPromotion(null); } }}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>{editingPromotion ? 'Edit Promotion' : 'Create Promotion'}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Promotion ID</Label>
              <Input value={formData.promotion_id} onChange={(e) => setFormData({ ...formData, promotion_id: e.target.value })} placeholder="e.g., summer_sale_2024" />
            </div>
            <div className="space-y-2">
              <Label>Title</Label>
              <Input value={formData.title} onChange={(e) => setFormData({ ...formData, title: e.target.value })} />
            </div>
            <div className="space-y-2">
              <Label>Message</Label>
              <Input value={formData.message} onChange={(e) => setFormData({ ...formData, message: e.target.value })} />
            </div>
            <div className="space-y-2">
              <Label>Link (optional)</Label>
              <Input value={formData.link} onChange={(e) => setFormData({ ...formData, link: e.target.value })} placeholder="https://..." />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Start Date</Label>
                <Input type="date" value={formData.start_date} onChange={(e) => setFormData({ ...formData, start_date: e.target.value })} />
              </div>
              <div className="space-y-2">
                <Label>End Date</Label>
                <Input type="date" value={formData.end_date} onChange={(e) => setFormData({ ...formData, end_date: e.target.value })} />
              </div>
            </div>
            <div className="space-y-2">
              <Label>Target Tier</Label>
              <Select value={formData.target_tier} onValueChange={(value: 'free' | 'pro') => setFormData({ ...formData, target_tier: value })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="free">Free Users</SelectItem>
                  <SelectItem value="pro">Pro Users</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="flex items-center gap-2">
              <Switch checked={formData.is_active} onCheckedChange={(checked) => setFormData({ ...formData, is_active: checked })} />
              <Label>Active</Label>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => { setIsCreating(false); setEditingPromotion(null); }}>Cancel</Button>
            <Button onClick={handleSubmit}>{editingPromotion ? 'Update' : 'Create'}</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
