import { useTranslation } from '@/hooks/use-translation';
import React, { useState } from 'react';
import { Head, Link, router } from '@inertiajs/react';
import AppLayout from '@/layouts/app-layout';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Plus, Search, Edit, Trash2, Eye, Calendar, CalendarPlus, FileText, AlertTriangle, CheckCircle, Clock, AlertCircle, Heart } from 'lucide-react';
import { type Note, type BreadcrumbItem } from '@/types';

const breadcrumbs: BreadcrumbItem[] = [
    {
        title: 'Dashboard',
        href: '/dashboard',
    },
    {
        title: 'Notes & Tasks',
        href: '/admin/notes',
    },
];

interface PaginationData {
    current_page: number;
    data: Note[];
    first_page_url: string;
    from: number;
    last_page: number;
    last_page_url: string;
    links: Array<{
        url?: string;
        label: string;
        active: boolean;
    }>;
    next_page_url?: string;
    path: string;
    per_page: number;
    prev_page_url?: string;
    to: number;
    total: number;
}

interface NoteStats {
    total: number;
    high_priority: number;
    medium_priority: number;
    low_priority: number;
    completed: number;
    pending: number;
    overdue: number;
}

interface Props {
    notes: PaginationData;
    stats: NoteStats;
    filters: {
        search?: string;
        assigned?: string;
    };
}

export default function NotesIndex({notes, stats, filters}: Readonly<Props>) {
    const { t } = useTranslation();
    const [search, setSearch] = useState(filters.search ?? '');
    
    const handleSearch = (e: React.FormEvent) => {
        e.preventDefault();
        router.get('/admin/notes', { search }, {
            preserveState: true,
            replace: true
        });
    };

    const handleDelete = (note: Note) => {
        if (confirm(`Are you sure you want to delete ${note.name}?`)) {
            router.delete(`/admin/notes/${note.id}`);
        }
    };

    const handleDownloadICS = (note: Note) => {
        window.location.assign(`/admin/notes/${note.id}/ics`);
    };

    const statCards = [
        {
            title: 'Total Notes',
            value: stats.total,
            icon: FileText,
            color: 'bg-blue-500',
            textColor: 'text-blue-600 dark:text-blue-400',
            bgColor: 'bg-blue-50 dark:bg-blue-900/20',
        },
        {
            title: 'Pending',
            value: stats.pending,
            icon: Clock,
            color: 'bg-yellow-500',
            textColor: 'text-yellow-600 dark:text-yellow-400',
            bgColor: 'bg-yellow-50 dark:bg-yellow-900/20',
        },
        {
            title: 'Completed',
            value: stats.completed,
            icon: CheckCircle,
            color: 'bg-green-500',
            textColor: 'text-green-600 dark:text-green-400',
            bgColor: 'bg-green-50 dark:bg-green-900/20',
        },
        {
            title: 'Overdue',
            value: stats.overdue,
            icon: AlertCircle,
            color: 'bg-red-500',
            textColor: 'text-red-600 dark:text-red-400',
            bgColor: 'bg-red-50 dark:bg-red-900/20',
            highlight: true,
        },
        {
            title: 'High Priority',
            value: stats.high_priority,
            icon: AlertTriangle,
            color: 'bg-red-500',
            textColor: 'text-red-600 dark:text-red-400',
            bgColor: 'bg-red-50 dark:bg-red-900/20',
            highlight: true,
        },
        {
            title: 'Medium Priority',
            value: stats.medium_priority,
            icon: AlertCircle,
            color: 'bg-orange-500',
            textColor: 'text-orange-600 dark:text-orange-400',
            bgColor: 'bg-orange-50 dark:bg-orange-900/20',
        },
        {
            title: 'Low Priority',
            value: stats.low_priority,
            icon: FileText,
            color: 'bg-gray-500',
            textColor: 'text-gray-600 dark:text-gray-400',
            bgColor: 'bg-gray-50 dark:bg-gray-900/20',
        },
    ];

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={t('Notes Management')} />
            <div className="flex h-full flex-1 flex-col gap-4 overflow-x-auto rounded-xl p-4">
          {/* Header */}
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                            {filters.assigned ? 'My Notes & Tasks' : 'Notes & Tasks'}
                        </h1>
                        <p className="text-gray-600 dark:text-gray-400">
                            {filters.assigned ? 'Notes and tasks assigned to you' : 'Manage notes and tasks'}
                        </p>
                    </div>
                    <div className="flex items-center space-x-2">
                        {filters.assigned && (
                            <Link href="/admin/notes">
                                <Button variant="outline">
                                    {t('View All Notes')}
                                </Button>
                            </Link>
                        )}
                        <Link href="/admin/notes/create">
                            <Button>
                                <Plus className="h-4 w-4 me-2" />
                                {t('Add Note')}
                            </Button>
                        </Link>
                    </div>
                </div>

                {/* Stats Dashboard */}
                <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4">
                    {statCards.map((stat) => (
                        <div
                            key={stat.title}
                            className={`bg-white dark:bg-black rounded-lg border ${
                                stat.highlight 
                                    ? 'border-2 ' + stat.color.replace('bg-', 'border-') 
                                    : 'border-gray-200 dark:border-gray-700'
                            } p-4 shadow-sm`}
                        >
                            <div className="flex flex-col items-center text-center">
                                <div className={`p-3 rounded-full ${stat.bgColor} mb-2`}>
                                    <stat.icon className={`h-6 w-6 ${stat.textColor}`} />
                                </div>
                                <p className="text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">
                                    {stat.title}
                                </p>
                                <p className={`text-2xl font-bold ${stat.textColor}`}>
                                    {stat.value}
                                </p>
                            </div>
                        </div>
                    ))}
                </div>

                {/* Search */}
        <div className="flex items-center space-x-4">
          <form onSubmit={handleSearch} className="flex items-center space-x-2 flex-1 max-w-md">
            <Input
              type="text"
              placeholder={t('Search notes...')}
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="flex-1"
            />
            <Button type="submit" variant="outline" size="sm">
              <Search className="h-4 w-4" />
            </Button>
          </form>

          {filters.search && (
            <Button variant="outline" onClick={() => {
              setSearch('');
              router.get('/admin/notes');
            }}>
              {t('Clear Filters')}
            </Button>
          )}
        </div>

        {/* Notes Table */}
        <div className="bg-white dark:bg-black shadow-sm rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
              <thead className="bg-gray-50 dark:bg-gray-700">
                <tr>
                  <th className="px-6 py-3 text-start text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    {t('Note')}
                  </th>
                  <th className="px-6 py-3 text-start text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    {t('Priority')}
                  </th>
                  <th className="px-6 py-3 text-start text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    {t('Deadline')}
                  </th>
                  <th className="px-6 py-3 text-start text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    {t('Status')}
                  </th>
                  <th className="px-6 py-3 text-end text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    {t('Actions')}
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white dark:bg-black divide-y divide-gray-200 dark:divide-gray-700">
                {notes.data.length > 0 ? (
                  notes.data.map((note) => (
                    <tr key={note.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div>
                          <div className="font-medium text-gray-900 dark:text-gray-100">
                            {note.name}
                          </div>
                          {note.note_text && (
                            <div className="text-sm text-gray-500 dark:text-gray-400 truncate max-w-xs">
                              {note.note_text}
                            </div>
                          )}
                          {note.label && (
                            <div className="mt-1">
                              <Badge variant="outline" className="text-xs">
                                {note.label}
                              </Badge>
                            </div>
                          )}
                          {note.member_care_alert && (
                            <div className="mt-1">
                              <Badge variant="destructive" className="text-xs">
                                <Heart className="h-3 w-3 me-1 inline" />
                                {note.member_care_alert === 'hospitalized' && 'Hospitalized'}
                                {note.member_care_alert === 'mourning' && 'Mourning'}
                                {note.member_care_alert === 'immediate_follow_up' && 'Immediate Follow-Up'}
                                {note.member_care_alert === 'other_emergency' && 'Other Emergency'}
                              </Badge>
                            </div>
                          )}
                          {note.member && (
                            <div className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                              Member: {note.member.first_name} {note.member.last_name}
                            </div>
                          )}
                          {note.user && (
                            <div className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                              Assigned: {note.user.name}
                            </div>
                          )}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <Badge variant={note.priority === 'high' ? 'destructive' : note.priority === 'medium' ? 'default' : 'secondary'}>
                          {note.priority}
                        </Badge>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        {note.deadline_date ? (
                          <div className="flex items-center text-gray-900 dark:text-gray-100">
                            <Calendar className="h-4 w-4 me-2 text-gray-400" />
                            <span className="text-sm">
                              {new Date(note.deadline_date).toLocaleDateString()}
                            </span>
                          </div>
                        ) : (
                          <span className="text-gray-500">{t('No deadline')}</span>
                        )}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        {note.completed_date ? (
                          <Badge variant="default">{t('Completed')}</Badge>
                        ) : note.deadline_date && new Date(note.deadline_date) < new Date() ? (
                          <Badge variant="destructive">{t('Overdue')}</Badge>
                        ) : (
                          <Badge variant="secondary">{t('Pending')}</Badge>
                        )}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-end text-sm font-medium">
                        <div className="flex items-center justify-end space-x-2">
                          <Link href={`/admin/notes/${note.id}`}>
                            <Button variant="outline" size="sm">
                              <Eye className="h-4 w-4" />
                            </Button>
                          </Link>
                          <Link href={`/admin/notes/${note.id}/edit`}>
                            <Button variant="outline" size="sm">
                              <Edit className="h-4 w-4" />
                            </Button>
                          </Link>
                          {!note.completed_date && note.deadline_date && (
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleDownloadICS(note)}
                              title={t('Add to calendar')}
                            >
                              <CalendarPlus className="h-4 w-4" />
                            </Button>
                          )}
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleDelete(note)}
                            className="text-red-600 hover:text-red-800"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan={5} className="px-6 py-12 text-center">
                      <div className="flex flex-col items-center">
                        <FileText className="h-12 w-12 text-gray-400 mb-4" />
                        <h3 className="text-lg font-medium text-gray-900 dark:text-gray-100">{t('No notes found')}</h3>
                        <p className="text-gray-600 dark:text-gray-400 mb-4">
                          {filters.search
                            ? 'No notes match your search criteria.'
                            : 'Get started by creating your first note.'}
                        </p>
                        <Link href="/admin/notes/create">
                          <Button>
                            <Plus className="h-4 w-4 me-2" />
                            {t('Create Note')}
                          </Button>
                        </Link>
                      </div>
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          {notes.last_page > 1 && (
            <div className="bg-white dark:bg-black px-4 py-3 border-t border-gray-200 dark:border-gray-700 sm:px-6">
              <div className="flex items-center justify-between">
                <div className="flex-1 flex justify-between sm:hidden">
                  {notes.prev_page_url && (
                    <Link href={notes.prev_page_url}>
                      <Button variant="outline">{t('Previous')}</Button>
                    </Link>
                  )}
                  {notes.next_page_url && (
                    <Link href={notes.next_page_url}>
                      <Button variant="outline">{t('Next')}</Button>
                    </Link>
                  )}
                </div>
                <div className="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                  <div>
                    <p className="text-sm text-gray-700 dark:text-gray-300">
                      Showing <span className="font-medium">{notes.from}</span> to{' '}
                      <span className="font-medium">{notes.to}</span> of{' '}
                      <span className="font-medium">{notes.total}</span> results
                    </p>
                  </div>
                  <div>
                    <nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                      {notes.links.map((link, index) => {
                        if (!link.url) {
                          return (
                            <span
                              key={index}
                              className="relative inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-black text-sm font-medium text-gray-500 dark:text-gray-400"
                              dangerouslySetInnerHTML={{ __html: link.label }}
                            />
                          );
                        }

                        return (
                          <Link
                            key={index}
                            href={link.url}
                            className={`relative inline-flex items-center px-4 py-2 border text-sm font-medium ${
                              link.active
                                ? 'z-10 bg-blue-50 border-blue-500 text-blue-600'
                                : 'bg-white dark:bg-black border-gray-300 dark:border-gray-600 text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700'
                            }`}
                            dangerouslySetInnerHTML={{ __html: link.label }}
                          />
                        );
                      })}
                    </nav>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
        </AppLayout>
    );
}