import { useState } from 'react';
import { motion } from 'framer-motion';
import {
  Plus,
  CheckCircle2,
  Circle,
  Clock,
  Phone,
  Mail,
  Calendar,
  MoreHorizontal,
  Filter,
  Search,
} from 'lucide-react';
import { mockTasks, mockContacts } from '@/lib/mock-data';
import { Task } from '@/lib/types';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { cn } from '@/lib/utils';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';

const typeIcons = {
  call: Phone,
  email: Mail,
  meeting: Calendar,
  'follow-up': Clock,
  other: MoreHorizontal,
};

const priorityConfig = {
  high: { label: 'High', className: 'bg-destructive/10 text-destructive border-destructive/20' },
  medium: { label: 'Medium', className: 'bg-warning/10 text-warning border-warning/20' },
  low: { label: 'Low', className: 'bg-muted text-muted-foreground border-border' },
};

export default function Tasks() {
  const [filter, setFilter] = useState<'all' | 'pending' | 'completed'>('all');
  const [searchQuery, setSearchQuery] = useState('');

  const filteredTasks = mockTasks.filter((task) => {
    if (filter === 'pending' && task.status === 'completed') return false;
    if (filter === 'completed' && task.status !== 'completed') return false;
    if (searchQuery) {
      return task.title.toLowerCase().includes(searchQuery.toLowerCase());
    }
    return true;
  });

  const formatDate = (date?: Date) => {
    if (!date) return '';
    const now = new Date();
    const diff = date.getTime() - now.getTime();
    const days = Math.ceil(diff / (1000 * 60 * 60 * 24));

    if (days < 0) return 'Overdue';
    if (days === 0) return 'Today';
    if (days === 1) return 'Tomorrow';
    return new Intl.DateTimeFormat('en-US', {
      month: 'short',
      day: 'numeric',
    }).format(date);
  };

  const getContact = (contactId?: string) => {
    return mockContacts.find((c) => c.id === contactId);
  };

  const getInitials = (firstName: string, lastName: string) => {
    return `${firstName[0]}${lastName[0]}`.toUpperCase();
  };

  return (
    <div className="p-6 space-y-6 animate-fade-in">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Tasks</h1>
          <p className="text-muted-foreground mt-1">
            Stay on top of your follow-ups and activities
          </p>
        </div>
        <Button className="gradient-primary shadow-glow gap-2">
          <Plus className="h-4 w-4" />
          Add Task
        </Button>
      </div>

      {/* Filters */}
      <div className="flex items-center gap-3">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Search tasks..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-9"
          />
        </div>
        <div className="flex items-center gap-1 rounded-lg border border-border p-1">
          {(['all', 'pending', 'completed'] as const).map((f) => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={cn(
                'px-3 py-1.5 text-sm font-medium rounded-md transition-colors',
                filter === f
                  ? 'bg-primary text-primary-foreground'
                  : 'text-muted-foreground hover:text-foreground'
              )}
            >
              {f.charAt(0).toUpperCase() + f.slice(1)}
            </button>
          ))}
        </div>
        <Button variant="outline" className="gap-2">
          <Filter className="h-4 w-4" />
          More Filters
        </Button>
      </div>

      {/* Tasks list */}
      <div className="rounded-xl border border-border bg-card divide-y divide-border">
        {filteredTasks.map((task, index) => {
          const TypeIcon = typeIcons[task.type];
          const contact = getContact(task.contactId);
          const priority = priorityConfig[task.priority];

          return (
            <motion.div
              key={task.id}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: index * 0.05 }}
              className="flex items-center gap-4 p-4 transition-colors hover:bg-accent/50 group"
            >
              <button className="text-muted-foreground hover:text-primary transition-colors">
                {task.status === 'completed' ? (
                  <CheckCircle2 className="h-5 w-5 text-success" />
                ) : (
                  <Circle className="h-5 w-5" />
                )}
              </button>

              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-3">
                  <p
                    className={cn(
                      'font-medium',
                      task.status === 'completed' &&
                        'line-through text-muted-foreground'
                    )}
                  >
                    {task.title}
                  </p>
                  <Badge
                    variant="outline"
                    className={cn('text-xs', priority.className)}
                  >
                    {priority.label}
                  </Badge>
                </div>
                {task.description && (
                  <p className="text-sm text-muted-foreground mt-1 truncate">
                    {task.description}
                  </p>
                )}
              </div>

              <div className="flex items-center gap-4">
                {contact && (
                  <div className="flex items-center gap-2">
                    <Avatar className="h-7 w-7">
                      <AvatarFallback className="bg-primary/10 text-primary text-xs">
                        {getInitials(contact.firstName, contact.lastName)}
                      </AvatarFallback>
                    </Avatar>
                    <span className="text-sm text-muted-foreground">
                      {contact.firstName} {contact.lastName}
                    </span>
                  </div>
                )}

                <Badge variant="secondary" className="gap-1">
                  <TypeIcon className="h-3 w-3" />
                  {task.type}
                </Badge>

                {task.dueDate && (
                  <span
                    className={cn(
                      'text-sm',
                      formatDate(task.dueDate) === 'Overdue' && 'text-destructive',
                      formatDate(task.dueDate) === 'Today' && 'text-warning'
                    )}
                  >
                    {formatDate(task.dueDate)}
                  </span>
                )}

                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="opacity-0 group-hover:opacity-100 transition-opacity"
                    >
                      <MoreHorizontal className="h-4 w-4" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end">
                    <DropdownMenuItem>Edit</DropdownMenuItem>
                    <DropdownMenuItem>Mark Complete</DropdownMenuItem>
                    <DropdownMenuItem>Reschedule</DropdownMenuItem>
                    <DropdownMenuItem className="text-destructive">
                      Delete
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
            </motion.div>
          );
        })}

        {filteredTasks.length === 0 && (
          <div className="p-12 text-center">
            <CheckCircle2 className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
            <h3 className="text-lg font-medium">No tasks found</h3>
            <p className="text-muted-foreground mt-1">
              {filter === 'completed'
                ? "You haven't completed any tasks yet"
                : 'Create a new task to get started'}
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
