'use client';

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

import { featureBenefitsApi, type FeatureBenefit } 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';

export default function FeatureBenefitsPage() {
  const queryClient = useQueryClient();
  const [params, setParams] = useState({ page: 1, per_page: 20, search: '' });
  const [search, setSearch] = useState('');
  const [editingBenefit, setEditingBenefit] = useState<FeatureBenefit | null>(null);
  const [isCreating, setIsCreating] = useState(false);
  const [formData, setFormData] = useState({
    feature_name: '',
    free_tier_text: '',
    pro_tier_text: '',
    display_order: 0,
    is_active: true,
  });

  const { data, isLoading } = useQuery({
    queryKey: ['feature-benefits', params],
    queryFn: () => featureBenefitsApi.list(params),
  });

  const createMutation = useMutation({
    mutationFn: featureBenefitsApi.create,
    onSuccess: () => {
      toast.success('Feature benefit created');
      queryClient.invalidateQueries({ queryKey: ['feature-benefits'] });
      setIsCreating(false);
      resetForm();
    },
    onError: () => toast.error('Failed to create feature benefit'),
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: any }) => featureBenefitsApi.update(id, data),
    onSuccess: () => {
      toast.success('Feature benefit updated');
      queryClient.invalidateQueries({ queryKey: ['feature-benefits'] });
      setEditingBenefit(null);
      resetForm();
    },
    onError: () => toast.error('Failed to update feature benefit'),
  });

  const deleteMutation = useMutation({
    mutationFn: featureBenefitsApi.delete,
    onSuccess: () => {
      toast.success('Feature benefit deleted');
      queryClient.invalidateQueries({ queryKey: ['feature-benefits'] });
    },
    onError: () => toast.error('Failed to delete feature benefit'),
  });

  const resetForm = () => {
    setFormData({ feature_name: '', free_tier_text: '', pro_tier_text: '', display_order: 0, is_active: true });
  };

  const handleEdit = (benefit: FeatureBenefit) => {
    setEditingBenefit(benefit);
    setFormData({
      feature_name: benefit.feature_name,
      free_tier_text: benefit.free_tier_text,
      pro_tier_text: benefit.pro_tier_text,
      display_order: benefit.display_order,
      is_active: benefit.is_active,
    });
  };

  const handleSubmit = () => {
    if (editingBenefit) {
      updateMutation.mutate({ id: editingBenefit.id, data: formData });
    } else {
      createMutation.mutate(formData);
    }
  };

  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">Feature Benefits</h1>
          <p className="text-muted-foreground">Manage subscription tier comparison features</p>
        </div>
        <Button onClick={() => { setIsCreating(true); resetForm(); }}>
          <Plus className="mr-2 h-4 w-4" />
          Add Feature
        </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</TableHead>
              <TableHead>Order</TableHead>
              <TableHead>Feature</TableHead>
              <TableHead>Free Tier</TableHead>
              <TableHead>Pro Tier</TableHead>
              <TableHead>Active</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 feature benefits found</TableCell></TableRow>
            ) : (
              data?.data?.map((benefit) => (
                <TableRow key={benefit.id}>
                  <TableCell className="font-mono text-sm text-muted-foreground">{benefit.id}</TableCell>
                  <TableCell>{benefit.display_order}</TableCell>
                  <TableCell className="font-medium">{benefit.feature_name}</TableCell>
                  <TableCell>{benefit.free_tier_text}</TableCell>
                  <TableCell>{benefit.pro_tier_text}</TableCell>
                  <TableCell>
                    <Badge variant={benefit.is_active ? 'default' : 'secondary'}>
                      {benefit.is_active ? 'Active' : 'Inactive'}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    {new Date(benefit.created_at).toLocaleDateString()}
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      <Button variant="ghost" size="icon" onClick={() => handleEdit(benefit)}>
                        <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 Feature?</AlertDialogTitle>
                            <AlertDialogDescription>This will permanently delete this feature benefit.</AlertDialogDescription>
                          </AlertDialogHeader>
                          <AlertDialogFooter>
                            <AlertDialogCancel>Cancel</AlertDialogCancel>
                            <AlertDialogAction onClick={() => deleteMutation.mutate(benefit.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 || !!editingBenefit} onOpenChange={(open) => { if (!open) { setIsCreating(false); setEditingBenefit(null); } }}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{editingBenefit ? 'Edit Feature Benefit' : 'Create Feature Benefit'}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Feature Name</Label>
              <Input value={formData.feature_name} onChange={(e) => setFormData({ ...formData, feature_name: e.target.value })} />
            </div>
            <div className="space-y-2">
              <Label>Free Tier Text</Label>
              <Input value={formData.free_tier_text} onChange={(e) => setFormData({ ...formData, free_tier_text: e.target.value })} />
            </div>
            <div className="space-y-2">
              <Label>Pro Tier Text</Label>
              <Input value={formData.pro_tier_text} onChange={(e) => setFormData({ ...formData, pro_tier_text: e.target.value })} />
            </div>
            <div className="space-y-2">
              <Label>Display Order</Label>
              <Input type="number" value={formData.display_order} onChange={(e) => setFormData({ ...formData, display_order: parseInt(e.target.value) || 0 })} />
            </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); setEditingBenefit(null); }}>Cancel</Button>
            <Button onClick={handleSubmit}>{editingBenefit ? 'Update' : 'Create'}</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
