import React, { useEffect } from 'react';
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Search, Play, Edit, Trash2, RefreshCw, FolderOpen, AlertCircle, Loader2 } from 'lucide-react';
import ApplyTemplateModal from './ApplyTemplateModal';
import WorkflowTemplateBuilder from './WorkflowTemplateBuilder';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { useWorkflowTemplates } from '@/hooks/useWorkflowTemplates';
import { useAuth } from '@/contexts/AuthContext';

export default function WorkflowTemplateList() {
  const { user } = useAuth();
  const [search, setSearch] = React.useState('');
  const [selectedTemplate, setSelectedTemplate] = React.useState(null);
  const [isApplyOpen, setIsApplyOpen] = React.useState(false);
  const [isEditOpen, setIsEditOpen] = React.useState(false);
  const [editingTemplate, setEditingTemplate] = React.useState(null);

  const { templates, loading, error, lastUpdated, getTemplates, deleteTemplate } = useWorkflowTemplates();

  useEffect(() => { getTemplates(); }, [getTemplates]);

  const handleRefresh = async () => { await getTemplates(); };

  const filteredTemplates = templates.filter(t =>
    t.name.toLowerCase().includes(search.toLowerCase()) ||
    (t.description && t.description.toLowerCase().includes(search.toLowerCase()))
  );

  const handleDeleteClick = async (id) => {
    if (window.confirm("Are you sure you want to delete this template?")) {
      await deleteTemplate(id);
    }
  };

  if (loading && templates.length === 0) {
    return (
      <div className="space-y-4">
        <div className="flex justify-between items-center"><Skeleton className="h-10 w-1/3" /><Skeleton className="h-10 w-10" /></div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {[1, 2, 3].map(i => (
            <Card key={i} className="flex flex-col"><CardHeader><Skeleton className="h-6 w-3/4 mb-2" /><Skeleton className="h-4 w-full" /></CardHeader>
              <CardContent><Skeleton className="h-4 w-1/2" /></CardContent><CardFooter className="pt-4 border-t"><Skeleton className="h-9 w-full" /></CardFooter></Card>
          ))}
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <Alert variant="destructive">
        <AlertCircle className="h-4 w-4" /><AlertTitle>Error Loading Templates</AlertTitle>
        <AlertDescription className="flex flex-col gap-3 mt-2">
          <p>{error}</p>
          <Button variant="outline" size="sm" onClick={handleRefresh} className="w-fit"><RefreshCw className="mr-2 h-3 w-3" /> Retry</Button>
        </AlertDescription>
      </Alert>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex flex-col sm:flex-row gap-3 justify-between items-end sm:items-center">
        <div className="relative flex-1 w-full">
          <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
          <Input placeholder="Search templates..." className="pl-9" value={search} onChange={e => setSearch(e.target.value)} />
        </div>
        <div className="flex items-center gap-3">
          {lastUpdated && (<span className="text-xs text-muted-foreground hidden md:inline-block">Updated: {lastUpdated.toLocaleTimeString()}</span>)}
          <Button variant="outline" size="sm" onClick={handleRefresh} disabled={loading} className="gap-2 min-w-[100px]">
            {loading ? <><Loader2 className="h-4 w-4 animate-spin" /> Refreshing...</> : <><RefreshCw className="h-4 w-4" /> Refresh</>}
          </Button>
          <Button onClick={() => { setEditingTemplate(null); setIsEditOpen(true); }} className="gap-2"><FolderOpen className="w-4 h-4" /> New Template</Button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {filteredTemplates.map(template => (
          <Card key={template.id} className="flex flex-col border hover:border-primary/30 transition-colors shadow-sm group">
            <CardHeader className="pb-2">
              <div className="flex justify-between items-start">
                <CardTitle className="text-lg font-semibold line-clamp-1">{template.name}</CardTitle>
                <Badge variant="secondary" className="shrink-0">{template.workflow_template_tasks?.length || 0} Tasks</Badge>
              </div>
              <CardDescription className="line-clamp-2 min-h-[40px] text-sm mt-1">{template.description || 'No description provided.'}</CardDescription>
            </CardHeader>
            <CardContent className="flex-1 py-2">
              <p className="text-xs text-muted-foreground">Created: {new Date(template.created_at).toLocaleDateString()}</p>
            </CardContent>
            <CardFooter className="flex justify-between items-center gap-2 pt-3 pb-3 px-4 border-t bg-muted/20 rounded-b-lg group-hover:bg-muted/40 transition-colors">
              <div className="flex gap-1">
                <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => { setEditingTemplate(template); setIsEditOpen(true); }}><Edit className="w-4 h-4" /></Button>
                <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive hover:bg-destructive/10" onClick={() => handleDeleteClick(template.id)}><Trash2 className="w-4 h-4" /></Button>
              </div>
              <Button size="sm" onClick={() => { setSelectedTemplate(template); setIsApplyOpen(true); }} className="gap-1"><Play className="w-3 h-3" /> Apply</Button>
            </CardFooter>
          </Card>
        ))}
        {!loading && filteredTemplates.length === 0 && (
          <div className="col-span-full flex flex-col items-center justify-center py-16 text-center border-2 border-dashed rounded-lg bg-muted/30">
            <div className="bg-card p-3 rounded-full mb-3 shadow-sm"><FolderOpen className="w-6 h-6 text-muted-foreground" /></div>
            <h3 className="text-lg font-medium">No templates found</h3>
            <p className="text-muted-foreground max-w-sm mt-1 mb-4">{search ? 'Try adjusting your search.' : 'Create your first workflow template.'}</p>
            {search ? <Button variant="outline" onClick={() => setSearch('')}>Clear Search</Button> : <Button onClick={() => setIsEditOpen(true)}>Create Template</Button>}
          </div>
        )}
      </div>

      <ApplyTemplateModal open={isApplyOpen} onOpenChange={setIsApplyOpen} template={selectedTemplate} onSuccess={handleRefresh} />
      <WorkflowTemplateBuilder open={isEditOpen} onOpenChange={setIsEditOpen} user={user} editTemplate={editingTemplate} onSuccess={() => { handleRefresh(); setEditingTemplate(null); }} />
    </div>
  );
}
