import { useState } from 'react';
import { 
  useLiveBlog, 
  useDeleteLiveBlogUpdate, 
  useUpdateLiveBlog,
  useDeleteLiveBlog 
} from '@/queries/live-blogs';
import { UpdatePublisher } from './UpdatePublisher';
import { LiveBlogUpdate } from '@/components/features/live-blog/LiveBlogUpdate';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import type { LiveBlogUpdate as ApiLiveBlogUpdate, UpdateLiveBlogDto } from '@/lib/api';
import { 
  ArrowLeft, 
  Edit, 
  Play, 
  Square, 
  Archive,
  Eye,
  MessageSquare,
  Pin,
  PinOff
} from 'lucide-react';

interface LiveBlogManagerProps {
  slug: string;
  onBack?: () => void;
  className?: string;
}

export function LiveBlogManager({ slug, onBack, className }: LiveBlogManagerProps) {
  const [activeTab, setActiveTab] = useState('updates');
  const [isEditing, setIsEditing] = useState(false);
  const [editForm, setEditForm] = useState<UpdateLiveBlogDto>({});
  
  const { data: liveBlog, isLoading, error } = useLiveBlog(slug);
  const deleteUpdateMutation = useDeleteLiveBlogUpdate();
  const updateLiveBlogMutation = useUpdateLiveBlog();
  const deleteLiveBlogMutation = useDeleteLiveBlog();



  const handleDeleteUpdate = async (update: ApiLiveBlogUpdate) => {
    if (!liveBlog) return;
    
    if (confirm('Are you sure you want to delete this update? This action cannot be undone.')) {
      try {
        await deleteUpdateMutation.mutateAsync({
          liveBlogId: liveBlog.id,
          updateId: update.id,
        });
      } catch (error) {
        console.error('Failed to delete update:', error);
      }
    }
  };

  const handleEditUpdate = (update: ApiLiveBlogUpdate) => {
    // The UpdatePublisher component handles editing internally
    console.log('Editing update:', update);
  };

  const handleStartEdit = () => {
    if (!liveBlog) return;
    
    setIsEditing(true);
    setEditForm({
      title: liveBlog.title,
      slug: liveBlog.slug,
      description: liveBlog.description || '',
      status: liveBlog.status,
    });
  };

  const handleCancelEdit = () => {
    setIsEditing(false);
    setEditForm({});
  };

  const handleSaveEdit = async () => {
    if (!liveBlog) return;
    
    try {
      await updateLiveBlogMutation.mutateAsync({
        id: liveBlog.id,
        dto: editForm,
      });
      setIsEditing(false);
      setEditForm({});
    } catch (error) {
      console.error('Failed to update live blog:', error);
    }
  };

  const handleStatusChange = async (newStatus: 'draft' | 'live' | 'ended' | 'archived') => {
    if (!liveBlog) return;
    
    try {
      await updateLiveBlogMutation.mutateAsync({
        id: liveBlog.id,
        dto: { status: newStatus },
      });
      
    } catch (error) {
      console.error('Failed to update status:', error);
      alert(`Failed to update status: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  };

  const handleTogglePin = async () => {
    if (!liveBlog) return;
    
    try {
      await updateLiveBlogMutation.mutateAsync({
        id: liveBlog.id,
        dto: { isPinned: !liveBlog.isPinned },
      });
      
    } catch (error) {
      console.error('Failed to toggle pin:', error);
      alert(`Failed to toggle pin: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  };

  const handleDeleteLiveBlog = async () => {
    if (!liveBlog) return;
    
    if (confirm('Are you sure you want to delete this live blog? This action cannot be undone and will delete all updates.')) {
      try {
        await deleteLiveBlogMutation.mutateAsync(liveBlog.id);
        if (onBack) onBack();
      } catch (error) {
        console.error('Failed to delete live blog:', error);
      }
    }
  };

  if (isLoading) {
    return (
      <Card className={className}>
        <CardContent className="p-6">
          <div className="animate-pulse space-y-4">
            <div className="h-8 bg-muted rounded w-3/4"></div>
            <div className="h-4 bg-muted rounded w-1/2"></div>
            <div className="h-32 bg-muted rounded"></div>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error || !liveBlog) {
    return (
      <Card className={className}>
        <CardContent className="p-6">
          <div className="text-center text-destructive">
            <h3 className="text-lg font-semibold mb-2">Failed to load live blog</h3>
            <p className="text-sm mb-4">
              {error instanceof Error ? error.message : 'Unknown error occurred'}
            </p>
            {onBack && (
              <Button variant="outline" onClick={onBack}>
                <ArrowLeft className="w-4 h-4 mr-2" />
                Back
              </Button>
            )}
          </div>
        </CardContent>
      </Card>
    );
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'live': return 'bg-green-100 text-green-800 border-green-200';
      case 'draft': return 'bg-gray-100 text-gray-800 border-gray-200';
      case 'ended': return 'bg-red-100 text-red-800 border-red-200';
      case 'archived': return 'bg-blue-100 text-blue-800 border-blue-200';
      default: return 'bg-gray-100 text-gray-800 border-gray-200';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'live': return <Play className="w-3 h-3" />;
      case 'draft': return <Edit className="w-3 h-3" />;
      case 'ended': return <Square className="w-3 h-3" />;
      case 'archived': return <Archive className="w-3 h-3" />;
      default: return null;
    }
  };

  return (
    <div className={className}>
      {/* Header */}
      <Card className="mb-6">
        <CardHeader>
          <div className="flex items-start justify-between">
            <div className="flex-1">
              <div className="flex items-center gap-3 mb-2">
                {onBack && (
                  <Button variant="ghost" size="sm" onClick={onBack}>
                    <ArrowLeft className="w-4 h-4" />
                  </Button>
                )}
                <CardTitle className="text-2xl">{liveBlog.title}</CardTitle>
              </div>
              
              {liveBlog.description && (
                <p className="text-muted-foreground mb-4">{liveBlog.description}</p>
              )}
              
              <div className="flex items-center gap-4 text-sm">
                <Badge className={getStatusColor(liveBlog.status)} variant="outline">
                  <div className="flex items-center gap-1">
                    {getStatusIcon(liveBlog.status)}
                    {liveBlog.status}
                  </div>
                </Badge>
                
                <div className="flex items-center gap-1 text-muted-foreground">
                  <Eye className="w-4 h-4" />
                  {liveBlog.viewCount} views
                </div>
                
                <div className="flex items-center gap-1 text-muted-foreground">
                  <MessageSquare className="w-4 h-4" />
                  {liveBlog.updates?.length || 0} updates
                </div>
                
                {liveBlog.author && (
                  <div className="flex items-center gap-2">
                    {liveBlog.author.avatar && (
                      <img
                        src={liveBlog.author.avatar}
                        alt={liveBlog.author.name}
                        className="w-6 h-6 rounded-full"
                      />
                    )}
                    <span className="text-muted-foreground">{liveBlog.author.name}</span>
                  </div>
                )}
              </div>
            </div>
          </div>
        </CardHeader>
      </Card>

      {/* Main content */}
      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="updates">Updates</TabsTrigger>
          <TabsTrigger value="settings">Settings</TabsTrigger>
        </TabsList>

        <TabsContent value="updates" className="space-y-6">
          <UpdatePublisher 
            liveBlogId={liveBlog.id}
            authorId={liveBlog.authorId || undefined}
          />
          
          {/* Recent updates preview */}
          {liveBlog.updates && liveBlog.updates.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">All Updates</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {liveBlog.updates.map((update) => (
                    <LiveBlogUpdate
                      key={update.id}
                      update={update}
                      showAdminControls={true}
                      onEdit={handleEditUpdate}
                      onDelete={handleDeleteUpdate}
                      onPinToggle={(update) => {
                        // Handle pin toggle
                        console.log('Toggle pin for update:', update);
                      }}
                    />
                  ))}
                </div>
              </CardContent>
            </Card>
          )}
        </TabsContent>

         <TabsContent value="settings" className="space-y-6">
           <Card>
             <CardHeader>
               <div className="flex items-center justify-between">
                 <CardTitle>Live Blog Settings</CardTitle>
                 {!isEditing ? (
                   <Button variant="outline" size="sm" onClick={handleStartEdit}>
                     <Edit className="w-4 h-4 mr-2" />
                     Edit
                   </Button>
                 ) : (
                   <div className="flex gap-2">
                     <Button variant="outline" size="sm" onClick={handleCancelEdit}>
                       Cancel
                     </Button>
                     <Button size="sm" onClick={handleSaveEdit}>
                       Save Changes
                     </Button>
                   </div>
                 )}
               </div>
             </CardHeader>
             <CardContent>
               <div className="space-y-6">
                 {isEditing ? (
                   <div className="space-y-4">
                     <div className="space-y-2">
                       <Label htmlFor="title">Title</Label>
                       <Input
                         id="title"
                         value={editForm.title || ''}
                         onChange={(e) => setEditForm({ ...editForm, title: e.target.value })}
                       />
                     </div>
                     
                     <div className="space-y-2">
                       <Label htmlFor="slug">Slug</Label>
                       <Input
                         id="slug"
                         value={editForm.slug || ''}
                         onChange={(e) => setEditForm({ ...editForm, slug: e.target.value })}
                         placeholder="URL-friendly identifier"
                       />
                     </div>
                     
                     <div className="space-y-2">
                       <Label htmlFor="description">Description</Label>
                       <Textarea
                         id="description"
                         value={editForm.description || ''}
                         onChange={(e) => setEditForm({ ...editForm, description: e.target.value })}
                         rows={3}
                       />
                     </div>
                     
                     <div className="space-y-2">
                       <Label htmlFor="status">Status</Label>
                       <Select
                         value={editForm.status}
                         onValueChange={(value: 'draft' | 'live' | 'ended' | 'archived') => 
                           setEditForm({ ...editForm, status: value })
                         }
                       >
                         <SelectTrigger>
                           <SelectValue placeholder="Select status" />
                         </SelectTrigger>
                         <SelectContent>
                           <SelectItem value="draft">Draft</SelectItem>
                           <SelectItem value="live">Live</SelectItem>
                           <SelectItem value="ended">Ended</SelectItem>
                           <SelectItem value="archived">Archived</SelectItem>
                         </SelectContent>
                       </Select>
                     </div>
                   </div>
                 ) : (
                   <>
                     <div className="p-4 bg-muted rounded-lg">
                       <h4 className="font-medium mb-2">Status Management</h4>
                       <p className="text-sm text-muted-foreground mb-4">
                         Control the live blog status and visibility
                       </p>
                        <div className="flex flex-wrap gap-2">
                          {liveBlog.status !== 'live' && (
                            <Button 
                              variant="outline" 
                              size="sm"
                              onClick={() => handleStatusChange('live')}
                              disabled={updateLiveBlogMutation.isPending}
                            >
                              <Play className="w-4 h-4 mr-2" />
                              {updateLiveBlogMutation.isPending ? 'Updating...' : 'Go Live'}
                            </Button>
                          )}
                          {liveBlog.status === 'live' && (
                            <Button 
                              variant="outline" 
                              size="sm"
                              onClick={() => handleStatusChange('ended')}
                              disabled={updateLiveBlogMutation.isPending}
                            >
                              <Square className="w-4 h-4 mr-2" />
                              {updateLiveBlogMutation.isPending ? 'Updating...' : 'End Live Session'}
                            </Button>
                          )}
                          {liveBlog.status !== 'archived' && (
                            <Button 
                              variant="outline" 
                              size="sm"
                              onClick={() => handleStatusChange('archived')}
                              disabled={updateLiveBlogMutation.isPending}
                            >
                              <Archive className="w-4 h-4 mr-2" />
                              {updateLiveBlogMutation.isPending ? 'Updating...' : 'Archive'}
                            </Button>
                          )}
                          {liveBlog.status === 'archived' && (
                            <Button 
                              variant="outline" 
                              size="sm"
                              onClick={() => handleStatusChange('draft')}
                              disabled={updateLiveBlogMutation.isPending}
                            >
                              <Edit className="w-4 h-4 mr-2" />
                              {updateLiveBlogMutation.isPending ? 'Updating...' : 'Unarchive'}
                            </Button>
                          )}
                          
                          <Button 
                            variant={liveBlog.isPinned ? "default" : "outline"}
                            size="sm"
                            onClick={handleTogglePin}
                            disabled={updateLiveBlogMutation.isPending}
                          >
                            {liveBlog.isPinned ? (
                              <>
                                <PinOff className="w-4 h-4 mr-2" />
                                {updateLiveBlogMutation.isPending ? 'Updating...' : 'Unpin'}
                              </>
                            ) : (
                              <>
                                <Pin className="w-4 h-4 mr-2" />
                                {updateLiveBlogMutation.isPending ? 'Updating...' : 'Pin to Homepage'}
                              </>
                            )}
                          </Button>
                        </div>
                     </div>
                     
                     <div className="p-4 bg-muted rounded-lg">
                       <h4 className="font-medium mb-2">Live Blog Information</h4>
                       <div className="space-y-3 text-sm">
                         <div className="flex justify-between">
                           <span className="text-muted-foreground">Title:</span>
                           <span className="font-medium">{liveBlog.title}</span>
                         </div>
                         <div className="flex justify-between">
                           <span className="text-muted-foreground">Slug:</span>
                           <span className="font-medium">{liveBlog.slug}</span>
                         </div>
                         {liveBlog.description && (
                           <div className="flex justify-between">
                             <span className="text-muted-foreground">Description:</span>
                             <span className="font-medium text-right max-w-xs">{liveBlog.description}</span>
                           </div>
                         )}
                          <div className="flex justify-between">
                            <span className="text-muted-foreground">Status:</span>
                            <Badge className={getStatusColor(liveBlog.status)} variant="outline">
                              <div className="flex items-center gap-1">
                                {getStatusIcon(liveBlog.status)}
                                {liveBlog.status}
                              </div>
                            </Badge>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-muted-foreground">Pinned:</span>
                            <Badge variant={liveBlog.isPinned ? "default" : "outline"}>
                              <div className="flex items-center gap-1">
                                {liveBlog.isPinned ? <Pin className="w-3 h-3" /> : <PinOff className="w-3 h-3" />}
                                {liveBlog.isPinned ? 'Yes' : 'No'}
                              </div>
                            </Badge>
                          </div>
                       </div>
                     </div>
                   </>
                 )}
                 
                 <div className="p-4 bg-muted rounded-lg">
                   <h4 className="font-medium mb-2">Analytics</h4>
                   <div className="grid grid-cols-2 gap-4 text-sm">
                     <div>
                       <span className="text-muted-foreground">Total Views:</span>
                       <div className="font-medium">{liveBlog.viewCount}</div>
                     </div>
                     <div>
                       <span className="text-muted-foreground">Total Updates:</span>
                       <div className="font-medium">{liveBlog.updates?.length || 0}</div>
                     </div>
                     <div>
                       <span className="text-muted-foreground">Created:</span>
                       <div className="font-medium">
                         {new Date(liveBlog.createdAt).toLocaleDateString()}
                       </div>
                     </div>
                     <div>
                       <span className="text-muted-foreground">Last Updated:</span>
                       <div className="font-medium">
                         {new Date(liveBlog.updatedAt).toLocaleDateString()}
                       </div>
                     </div>
                   </div>
                 </div>
                 
                 <div className="p-4 border border-destructive/20 rounded-lg">
                   <h4 className="font-medium mb-2 text-destructive">Danger Zone</h4>
                   <p className="text-sm text-muted-foreground mb-4">
                     Once you delete a live blog, there is no going back. Please be certain.
                   </p>
                   <Button 
                     variant="destructive" 
                     size="sm"
                     onClick={handleDeleteLiveBlog}
                     disabled={deleteLiveBlogMutation.isPending}
                   >
                     {deleteLiveBlogMutation.isPending ? 'Deleting...' : 'Delete Live Blog'}
                   </Button>
                 </div>
               </div>
             </CardContent>
           </Card>
         </TabsContent>
      </Tabs>
    </div>
  );
}