import React, { useState, useEffect, useCallback } from 'react';
import {
  Search,
  FileText,
  Loader2,
} from 'lucide-react';
import { toast } from 'sonner';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { focusGroupsApi } from '@/lib/api';

interface CopyGuideDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onCopyGuide: (focusGroup: any) => void;
  excludeFocusGroupId?: string | null;
}

export function CopyGuideDialog({
  open,
  onOpenChange,
  onCopyGuide,
  excludeFocusGroupId,
}: CopyGuideDialogProps) {
  const [searchTerm, setSearchTerm] = useState('');
  const [availableFocusGroups, setAvailableFocusGroups] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(false);

  // Fetch available focus groups when dialog opens
  const fetchAvailableFocusGroups = useCallback(async () => {
    try {
      setIsLoading(true);
      const response = await focusGroupsApi.getAll();

      // Filter to only include focus groups that have discussion guides
      const focusGroupsWithGuides = response.data.filter((fg: any) =>
        fg.discussionGuide &&
        fg.discussionGuide !== null &&
        fg.discussionGuide !== '' &&
        fg._id !== excludeFocusGroupId
      );

      setAvailableFocusGroups(focusGroupsWithGuides);
    } catch (error) {
      console.error("Error fetching focus groups:", error);
      toast.error("Failed to load available focus groups");
    } finally {
      setIsLoading(false);
    }
  }, [excludeFocusGroupId]);

  // Fetch when dialog opens
  useEffect(() => {
    if (open) {
      fetchAvailableFocusGroups();
    }
  }, [open, fetchAvailableFocusGroups]);

  // Filter by search term
  const filteredFocusGroups = availableFocusGroups.filter(fg =>
    !searchTerm || fg.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const handleSelectFocusGroup = (focusGroup: any) => {
    onCopyGuide(focusGroup);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Import Discussion Guide from Other Project</DialogTitle>
          <DialogDescription>
            Select a focus group to import its discussion guide from. Only focus groups with existing discussion guides are shown.
          </DialogDescription>
        </DialogHeader>

        <div className="py-4 space-y-4">
          {/* Search box */}
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
            <Input
              placeholder="Search focus groups by name..."
              className="pl-10"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>

          {/* Loading state */}
          {isLoading && (
            <div className="flex justify-center items-center py-8">
              <Loader2 className="h-8 w-8 animate-spin text-primary" />
              <span className="ml-2 text-muted-foreground">Loading focus groups...</span>
            </div>
          )}

          {/* Focus groups list */}
          {!isLoading && (
            <div className="space-y-3 max-h-96 overflow-y-auto">
              {filteredFocusGroups.length > 0 ? (
                filteredFocusGroups.map((focusGroup) => (
                  <Card
                    key={focusGroup._id}
                    className="p-4 cursor-pointer hover:bg-muted/50 transition-colors"
                    onClick={() => handleSelectFocusGroup(focusGroup)}
                  >
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <h3 className="font-medium text-sm">{focusGroup.name}</h3>
                        <Badge variant="outline" className="text-xs">
                          {focusGroup.participants_count || focusGroup.participants?.length || 0} participants
                        </Badge>
                      </div>

                      {focusGroup.description && (
                        <p className="text-xs text-muted-foreground line-clamp-2">
                          {focusGroup.description}
                        </p>
                      )}

                      <div className="flex items-center gap-4 text-xs text-muted-foreground">
                        {focusGroup.created_at && (
                          <span>Created {new Date(focusGroup.created_at).toLocaleDateString()}</span>
                        )}
                        {focusGroup.duration && (
                          <span>{focusGroup.duration} minutes</span>
                        )}
                        {focusGroup.status && (
                          <Badge variant="secondary" className="text-xs">
                            {focusGroup.status}
                          </Badge>
                        )}
                      </div>
                    </div>
                  </Card>
                ))
              ) : (
                <div className="text-center py-8">
                  <FileText className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
                  <p className="text-muted-foreground">
                    {searchTerm
                      ? "No focus groups match your search criteria."
                      : "No focus groups with discussion guides found."}
                  </p>
                  {searchTerm && (
                    <Button
                      variant="link"
                      size="sm"
                      onClick={() => setSearchTerm('')}
                      className="mt-2"
                    >
                      Clear search
                    </Button>
                  )}
                </div>
              )}
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

export default CopyGuideDialog;
