import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Loader2, Search, FileText, Calendar, User, Eye, EyeOff } from 'lucide-react';
import { listSharedSummaries, markAsViewed, type SharedSummary } from '@/services/summaryApi';
import { format } from 'date-fns';
import { toast } from 'sonner';

interface SharedSummariesProps {
  onViewSummary?: (sharedSummaryId: string) => void;
}

export function SharedSummaries({ onViewSummary }: SharedSummariesProps) {
  const navigate = useNavigate();
  const [summaries, setSummaries] = useState<SharedSummary[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalRecords, setTotalRecords] = useState(0);
  const itemsPerPage = 10;

  const fetchSummaries = useCallback(async (page: number = 1) => {
    try {
      setLoading(true);
      const result = await listSharedSummaries({ page, limit: itemsPerPage });
      setSummaries(result.data || []);
      setTotalPages(result.pagination.totalPages || 1);
      setTotalRecords(result.pagination.total || 0);
      setCurrentPage(result.pagination.page || 1);
    } catch (error: any) {
      console.error('Failed to fetch shared summaries:', error);
      toast.error('Failed to load shared summaries');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchSummaries(1);
  }, [fetchSummaries]);

  const handleViewSummary = async (sharedSummaryId: string) => {
    try {
      // Mark as viewed
      await markAsViewed(sharedSummaryId);
      // Update local state
      setSummaries(prev => prev.map(s => 
        s.sharedSummaryId === sharedSummaryId 
          ? { ...s, isRead: true, viewedAt: new Date().toISOString() }
          : s
      ));
      // Navigate to detail view
      if (onViewSummary) {
        onViewSummary(sharedSummaryId);
      } else {
        navigate(`/shared-summaries/${sharedSummaryId}`);
      }
    } catch (error: any) {
      console.error('Failed to mark as viewed:', error);
      // Still navigate even if marking as viewed fails
      if (onViewSummary) {
        onViewSummary(sharedSummaryId);
      } else {
        navigate(`/shared-summaries/${sharedSummaryId}`);
      }
    }
  };

  const handlePageChange = (newPage: number) => {
    if (newPage >= 1 && newPage <= totalPages) {
      fetchSummaries(newPage);
    }
  };

  const filteredSummaries = summaries.filter(summary => {
    if (!searchTerm) return true;
    const search = searchTerm.toLowerCase();
    return (
      summary.title?.toLowerCase().includes(search) ||
      summary.requestNumber?.toLowerCase().includes(search) ||
      summary.initiatorName?.toLowerCase().includes(search) ||
      summary.sharedByName?.toLowerCase().includes(search)
    );
  });

  return (
    <div className="min-h-screen bg-gray-50 p-3 sm:p-4 md:p-6 overflow-x-hidden">
      <div className="max-w-7xl mx-auto w-full">
        {/* Header */}
        <div className="mb-4 sm:mb-6">
          <h1 className="text-xl sm:text-2xl md:text-3xl font-bold text-gray-900 mb-1 sm:mb-2">Shared Summaries</h1>
          <p className="text-xs sm:text-sm text-gray-600">View summaries of closed requests shared with you</p>
        </div>

        {/* Search */}
        <div className="mb-4 sm:mb-6">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <Input
              placeholder="Search by title, request number, or user..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10 text-sm sm:text-base"
            />
          </div>
        </div>

        {/* Loading State */}
        {loading && (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
          </div>
        )}

        {/* Summaries List */}
        {!loading && filteredSummaries.length === 0 && (
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 sm:p-12 text-center">
            <FileText className="h-8 w-8 sm:h-12 sm:w-12 text-gray-400 mx-auto mb-3 sm:mb-4" />
            <h3 className="text-base sm:text-lg font-semibold text-gray-900 mb-1 sm:mb-2">No shared summaries</h3>
            <p className="text-sm sm:text-base text-gray-600">
              {searchTerm ? 'No summaries match your search.' : 'You haven\'t received any shared summaries yet.'}
            </p>
          </div>
        )}

        {!loading && filteredSummaries.length > 0 && (
          <>
            <div className="grid gap-3 sm:gap-4 mb-4 sm:mb-6">
              {filteredSummaries.map((summary) => (
                <div
                  key={summary.sharedSummaryId}
                  className={`bg-white rounded-lg shadow-sm border-2 transition-all cursor-pointer hover:shadow-md ${
                    summary.isRead ? 'border-gray-200' : 'border-blue-300 bg-blue-50'
                  }`}
                  onClick={() => handleViewSummary(summary.sharedSummaryId)}
                >
                  <div className="p-3 sm:p-4 md:p-6">
                    <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3 sm:gap-4">
                      <div className="flex-1 min-w-0 w-full sm:w-auto">
                        <div className="flex items-center gap-2 mb-2 flex-wrap">
                          {summary.isRead ? (
                            <EyeOff className="h-4 w-4 text-gray-400 flex-shrink-0" />
                          ) : (
                            <Eye className="h-4 w-4 text-blue-600 flex-shrink-0" />
                          )}
                          <h3 className="text-base sm:text-lg font-semibold text-gray-900 truncate flex-1 min-w-0">
                            {summary.title}
                          </h3>
                          {!summary.isRead && (
                            <span className="px-2 py-0.5 bg-blue-100 text-blue-700 text-xs font-medium rounded-full flex-shrink-0">
                              New
                            </span>
                          )}
                        </div>
                        <p className="text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 break-words">
                          Request: <span className="font-medium">{summary.requestNumber}</span>
                        </p>
                        <div className="flex flex-col sm:flex-row sm:flex-wrap items-start sm:items-center gap-2 sm:gap-3 md:gap-4 text-xs sm:text-sm text-gray-500">
                          <div className="flex items-center gap-1 min-w-0">
                            <User className="h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0" />
                            <span className="truncate">Initiator: <span className="font-medium">{summary.initiatorName}</span></span>
                          </div>
                          <div className="flex items-center gap-1 min-w-0">
                            <User className="h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0" />
                            <span className="truncate">Shared by: <span className="font-medium">{summary.sharedByName}</span></span>
                          </div>
                          <div className="flex items-center gap-1 min-w-0">
                            <Calendar className="h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0" />
                            <span className="truncate">
                              Shared: {format(new Date(summary.sharedAt), 'MMM dd, yyyy HH:mm')}
                            </span>
                          </div>
                          {summary.viewedAt && (
                            <div className="flex items-center gap-1 min-w-0">
                              <Eye className="h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0" />
                              <span className="truncate">
                                Viewed: {format(new Date(summary.viewedAt), 'MMM dd, yyyy HH:mm')}
                              </span>
                            </div>
                          )}
                        </div>
                      </div>
                      <Button
                        variant="outline"
                        size="sm"
                        className="w-full sm:w-auto flex-shrink-0"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleViewSummary(summary.sharedSummaryId);
                        }}
                      >
                        View
                      </Button>
                    </div>
                  </div>
                </div>
              ))}
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 sm:gap-4 bg-white rounded-lg shadow-sm border border-gray-200 p-3 sm:p-4">
                <div className="text-xs sm:text-sm text-gray-600 text-center sm:text-left">
                  Showing {((currentPage - 1) * itemsPerPage) + 1} to {Math.min(currentPage * itemsPerPage, totalRecords)} of {totalRecords} summaries
                </div>
                <div className="flex items-center justify-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handlePageChange(currentPage - 1)}
                    disabled={currentPage === 1}
                    className="text-xs sm:text-sm"
                  >
                    Previous
                  </Button>
                  <span className="text-xs sm:text-sm text-gray-600 whitespace-nowrap">
                    Page {currentPage} of {totalPages}
                  </span>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handlePageChange(currentPage + 1)}
                    disabled={currentPage === totalPages}
                    className="text-xs sm:text-sm"
                  >
                    Next
                  </Button>
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}

