'use client';

import { useState } from 'react';
import { useAppStore } from '@/lib/store';
import { t } from '@/lib/i18n';
import { mockCommunityPosts } from '@/lib/mock-data';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogClose,
} from '@/components/ui/dialog';
import {
  ArrowLeft,
  Users,
  Plus,
  Heart,
  MessageCircle,
  HelpCircle,
  Lightbulb,
  MessagesSquare,
  Send,
} from 'lucide-react';

type PostType = 'discussion' | 'help' | 'suggestion';
type FilterTab = 'all' | PostType;

interface CommunityPost {
  id: string;
  author: string;
  title: string;
  content: string;
  type: PostType;
  likes: number;
  time: string;
  comments: number;
}

const postTypeConfig: Record<PostType, { color: string; icon: React.ElementType; labelKey: string }> = {
  discussion: {
    color: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400',
    icon: MessagesSquare,
    labelKey: 'community.discussions',
  },
  help: {
    color: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
    icon: HelpCircle,
    labelKey: 'community.help',
  },
  suggestion: {
    color: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
    icon: Lightbulb,
    labelKey: 'community.suggestions',
  },
};

const filterTabs: { key: FilterTab; labelKey: string }[] = [
  { key: 'all', labelKey: '' },
  { key: 'discussion', labelKey: 'community.discussions' },
  { key: 'help', labelKey: 'community.help' },
  { key: 'suggestion', labelKey: 'community.suggestions' },
];

function PostCard({ post, language }: { post: CommunityPost; language: 'en' | 'bn' }) {
  const [liked, setLiked] = useState(false);
  const [likeCount, setLikeCount] = useState(post.likes);
  const config = postTypeConfig[post.type];
  const TypeIcon = config.icon;

  const handleLike = () => {
    if (liked) {
      setLikeCount((prev) => prev - 1);
    } else {
      setLikeCount((prev) => prev + 1);
    }
    setLiked(!liked);
  };

  const initials = post.author
    .split(' ')
    .map((n) => n[0])
    .join('')
    .toUpperCase()
    .slice(0, 2);

  return (
    <Card className="overflow-hidden transition-shadow duration-200 hover:shadow-md">
      <CardContent className="p-4">
        {/* Author Row */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Avatar className="h-9 w-9">
              <AvatarFallback className="bg-primary/10 text-xs font-semibold text-primary">
                {initials}
              </AvatarFallback>
            </Avatar>
            <div>
              <p className="text-sm font-medium text-foreground">{post.author}</p>
              <p className="text-[11px] text-muted-foreground">{post.time}</p>
            </div>
          </div>
          <Badge variant="secondary" className={`border-0 text-[10px] font-medium ${config.color}`}>
            <TypeIcon className="mr-1 h-3 w-3" />
            {t(config.labelKey, language)}
          </Badge>
        </div>

        {/* Content */}
        <div className="mt-3">
          <h3 className="text-sm font-semibold text-foreground leading-snug">{post.title}</h3>
          <p className="mt-1.5 text-xs text-muted-foreground leading-relaxed line-clamp-3">
            {post.content}
          </p>
        </div>

        {/* Actions */}
        <div className="mt-3 flex items-center gap-4">
          <button
            onClick={handleLike}
            className={`flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium transition-colors duration-150 ${
              liked
                ? 'bg-red-50 text-red-500 dark:bg-red-900/20 dark:text-red-400'
                : 'bg-muted text-muted-foreground hover:bg-accent hover:text-foreground'
            }`}
          >
            <Heart className={`h-3.5 w-3.5 ${liked ? 'fill-current' : ''}`} />
            {likeCount}
          </button>
          <button className="flex items-center gap-1.5 rounded-full bg-muted px-3 py-1.5 text-xs font-medium text-muted-foreground transition-colors duration-150 hover:bg-accent hover:text-foreground">
            <MessageCircle className="h-3.5 w-3.5" />
            {post.comments}
          </button>
        </div>
      </CardContent>
    </Card>
  );
}

export default function CommunityModule() {
  const { language, setCurrentSection } = useAppStore();
  const [activeTab, setActiveTab] = useState<FilterTab>('all');
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [newTitle, setNewTitle] = useState('');
  const [newContent, setNewContent] = useState('');
  const [newType, setNewType] = useState<PostType>('discussion');

  const [posts, setPosts] = useState<CommunityPost[]>(mockCommunityPosts as CommunityPost[]);

  const filteredPosts =
    activeTab === 'all'
      ? posts
      : posts.filter((post) => post.type === activeTab);

  const handleCreatePost = () => {
    if (!newTitle.trim() || !newContent.trim()) return;

    const newPost: CommunityPost = {
      id: `cp${Date.now()}`,
      author: 'You',
      title: newTitle.trim(),
      content: newContent.trim(),
      type: newType,
      likes: 0,
      time: language === 'en' ? 'Just now' : 'এইমাত্র',
      comments: 0,
    };

    setPosts((prev) => [newPost, ...prev]);
    setNewTitle('');
    setNewContent('');
    setNewType('discussion');
    setShowCreateDialog(false);
  };

  return (
    <div className="flex min-h-[calc(100vh-8rem)] flex-col">
      {/* Header */}
      <div className="bg-gradient-to-br from-primary via-primary/90 to-primary/70 px-6 pb-6 pt-6">
        <div className="flex items-center gap-3">
          <Button variant="ghost" size="icon" onClick={() => setCurrentSection('home')} className="shrink-0 text-primary-foreground hover:bg-primary-foreground/20">
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-primary-foreground/20">
            <Users className="h-5 w-5 text-primary-foreground" strokeWidth={1.75} />
          </div>
          <div>
            <h1 className="text-xl font-bold text-primary-foreground">
              {t('community.title', language)}
            </h1>
            <p className="text-xs text-primary-foreground/70">
              {language === 'en' ? 'Connect, share & help each other' : 'সংযোগ করুন, শেয়ার করুন ও সাহায্য করুন'}
            </p>
          </div>
        </div>
      </div>

      {/* Filter Tabs */}
      <div className="sticky top-0 z-10 border-b bg-background px-4 py-2">
        <div className="scrollbar-hide flex gap-2 overflow-x-auto pb-1">
          <button
            onClick={() => setActiveTab('all')}
            className={`shrink-0 rounded-full px-4 py-1.5 text-xs font-medium transition-colors duration-150 ${
              activeTab === 'all'
                ? 'bg-primary text-primary-foreground shadow-sm'
                : 'bg-muted text-muted-foreground hover:bg-accent'
            }`}
          >
            {language === 'en' ? 'All' : 'সব'}
          </button>
          {filterTabs.slice(1).map((tab) => {
            const tabConfig = postTypeConfig[tab.key as PostType];
            const TabIcon = tabConfig?.icon;
            return (
              <button
                key={tab.key}
                onClick={() => setActiveTab(tab.key)}
                className={`flex shrink-0 items-center gap-1.5 rounded-full px-4 py-1.5 text-xs font-medium transition-colors duration-150 ${
                  activeTab === tab.key
                    ? 'bg-primary text-primary-foreground shadow-sm'
                    : 'bg-muted text-muted-foreground hover:bg-accent'
                }`}
              >
                {TabIcon && <TabIcon className="h-3 w-3" />}
                {t(tab.labelKey, language)}
              </button>
            );
          })}
        </div>
      </div>

      {/* Posts List */}
      <div className="flex-1 px-4 py-4 pb-24">
        {filteredPosts.length > 0 ? (
          <div className="space-y-3">
            {filteredPosts.map((post) => (
              <PostCard key={post.id} post={post} language={language} />
            ))}
          </div>
        ) : (
          <div className="flex flex-col items-center justify-center gap-4 py-20">
            <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-muted">
              <MessageCircle className="h-8 w-8 text-muted-foreground" strokeWidth={1.5} />
            </div>
            <div className="text-center">
              <p className="text-sm font-medium text-foreground">
                {t('common.noResults', language)}
              </p>
              <p className="mt-1 text-xs text-muted-foreground">
                {language === 'en'
                  ? 'No posts in this category'
                  : 'এই বিভাগে কোনো পোস্ট নেই'}
              </p>
            </div>
          </div>
        )}
      </div>

      {/* Floating Create Post Button */}
      <button
        onClick={() => setShowCreateDialog(true)}
        className="fixed bottom-24 right-6 z-20 flex h-14 w-14 items-center justify-center rounded-full bg-gradient-to-br from-primary to-primary/90 shadow-lg shadow-primary/30 transition-transform duration-150 hover:scale-105 active:scale-95 sm:right-8"
        aria-label={t('community.createPost', language)}
      >
        <Plus className="h-6 w-6 text-primary-foreground" strokeWidth={2.5} />
      </button>

      {/* Create Post Dialog */}
      <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader className="flex-row items-center gap-2 space-y-0">
            <Button variant="ghost" size="sm" onClick={() => setShowCreateDialog(false)} className="gap-1.5 text-orange-600 hover:text-orange-700 hover:bg-orange-50 dark:text-orange-400 dark:hover:bg-orange-950/30 -ml-2">
              <ArrowLeft className="h-4 w-4" />
              <span>{language === 'en' ? 'Back' : 'ফিরুন'}</span>
            </Button>
            <DialogTitle className="flex items-center gap-2">
              <Send className="h-5 w-5 text-primary" />
              {t('community.createPost', language)}
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-4">
            {/* Post Type Selection */}
            <div className="space-y-2">
              <Label className="text-xs font-medium">
                {language === 'en' ? 'Post Type' : 'পোস্টের ধরন'}
              </Label>
              <div className="flex gap-2">
                {(Object.keys(postTypeConfig) as PostType[]).map((type) => {
                  const cfg = postTypeConfig[type];
                  const TypeIcon = cfg.icon;
                  return (
                    <button
                      key={type}
                      onClick={() => setNewType(type)}
                      className={`flex flex-1 items-center justify-center gap-1.5 rounded-lg border px-3 py-2 text-xs font-medium transition-colors duration-150 ${
                        newType === type
                          ? 'border-primary bg-primary/5 text-primary'
                          : 'border-border text-muted-foreground hover:border-primary/30 hover:bg-accent'
                      }`}
                    >
                      <TypeIcon className="h-3.5 w-3.5" />
                      {t(cfg.labelKey, language)}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Title */}
            <div className="space-y-2">
              <Label htmlFor="post-title" className="text-xs font-medium">
                {language === 'en' ? 'Title' : 'শিরোনাম'}
              </Label>
              <Input
                id="post-title"
                placeholder={language === 'en' ? 'What do you want to share?' : 'আপনি কী শেয়ার করতে চান?'}
                value={newTitle}
                onChange={(e) => setNewTitle(e.target.value)}
                className="text-sm"
              />
            </div>

            {/* Content */}
            <div className="space-y-2">
              <Label htmlFor="post-content" className="text-xs font-medium">
                {language === 'en' ? 'Content' : 'বিষয়বস্তু'}
              </Label>
              <Textarea
                id="post-content"
                placeholder={language === 'en' ? 'Write your thoughts...' : 'আপনার চিন্তা লিখুন...'}
                value={newContent}
                onChange={(e) => setNewContent(e.target.value)}
                className="min-h-[100px] text-sm resize-none"
              />
            </div>
          </div>

          <DialogFooter className="gap-2 sm:gap-0">
            <DialogClose asChild>
              <Button variant="outline" size="sm">
                {t('common.cancel', language)}
              </Button>
            </DialogClose>
            <Button
              onClick={handleCreatePost}
              disabled={!newTitle.trim() || !newContent.trim()}
              size="sm"
              className="bg-gradient-to-r from-primary to-primary/90"
            >
              <Send className="mr-1.5 h-3.5 w-3.5" />
              {t('common.submit', language)}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
