import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { DragDropContext, Droppable, Draggable } from '@hello-pangea/dnd';
import { GripVertical, Plus, Trash2, Loader2, Save } from 'lucide-react';
import { useWorkflowTemplates } from '@/hooks/useWorkflowTemplates';
import { useToast } from '@/hooks/use-toast';
import { Alert, AlertDescription } from '@/components/ui/alert';

export default function WorkflowTemplateBuilder({ open, onOpenChange, user, onSuccess, editTemplate = null }) {
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [tasks, setTasks] = useState([]);
  const [error, setError] = useState('');
  const { createTemplate, loading } = useWorkflowTemplates();
  const { toast } = useToast();

  useEffect(() => {
    if (open) {
      setError('');
      if (editTemplate) {
        setName(editTemplate.name || '');
        setDescription(editTemplate.description || '');
        const sorted = [...(editTemplate.workflow_template_tasks || [])].sort((a, b) => a.task_sequence - b.task_sequence);
        setTasks(sorted.map(t => ({ id: t.id || `temp-${Math.random()}`, task_name: t.task_name, task_description: t.task_description || '', days_until_due: t.days_until_due || 0, priority: t.priority || 'medium' })));
      } else {
        setName(''); setDescription(''); setTasks([]);
      }
    }
  }, [open, editTemplate]);

  const handleAddTask = () => {
    setTasks([...tasks, { id: `temp-${Date.now()}`, task_name: '', task_description: '', days_until_due: 0, priority: 'medium' }]);
  };

  const handleTaskChange = (index, field, value) => {
    const newTasks = [...tasks]; newTasks[index][field] = value; setTasks(newTasks);
  };

  const handleRemoveTask = (index) => { setTasks(tasks.filter((_, i) => i !== index)); };

  const onDragEnd = (result) => {
    if (!result.destination) return;
    const items = Array.from(tasks);
    const [reorderedItem] = items.splice(result.source.index, 1);
    items.splice(result.destination.index, 0, reorderedItem);
    setTasks(items);
  };

  const handleSave = async () => {
    setError('');
    if (!name.trim()) { setError("Template name is required."); return; }
    if (tasks.length === 0) { setError("Please add at least one task."); return; }
    for (let i = 0; i < tasks.length; i++) {
      if (!tasks[i].task_name.trim()) { setError(`Task #${i + 1} must have a name.`); return; }
    }

    const templateData = { name: name.trim(), description: description.trim() };
    const cleanTasks = tasks.map(t => ({ task_name: t.task_name, task_description: t.task_description, days_until_due: t.days_until_due, priority: t.priority }));
    const success = await createTemplate(templateData, cleanTasks);
    if (success) {
      toast({ title: "Success", description: "Template saved successfully" });
      if (onSuccess) onSuccess();
      onOpenChange(false);
      setName(''); setDescription(''); setTasks([]);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] flex flex-col">
        <DialogHeader>
          <DialogTitle>{editTemplate ? 'Edit Workflow Template' : 'Create Workflow Template'}</DialogTitle>
          <DialogDescription>Define a reusable set of tasks for your team.</DialogDescription>
        </DialogHeader>
        {error && (<Alert variant="destructive" className="mb-2"><AlertDescription>{error}</AlertDescription></Alert>)}
        <div className="flex-1 overflow-y-auto pr-2">
          <div className="space-y-4 py-4">
            <div className="grid gap-2">
              <Label>Template Name <span className="text-destructive">*</span></Label>
              <Input value={name} onChange={e => setName(e.target.value)} placeholder="e.g. New Homeowner Onboarding" className="font-medium" />
            </div>
            <div className="grid gap-2">
              <Label>Description</Label>
              <Textarea value={description} onChange={e => setDescription(e.target.value)} placeholder="Describe the purpose..." />
            </div>
            <div className="space-y-3 pt-4 border-t">
              <div className="flex justify-between items-center bg-muted/50 p-2 rounded-md border">
                <div className="flex flex-col">
                  <span className="font-semibold text-sm">Workflow Tasks</span>
                  <span className="text-xs text-muted-foreground">{tasks.length} tasks defined</span>
                </div>
                <Button size="sm" onClick={handleAddTask} className="gap-1"><Plus className="w-3 h-3" /> Add Task</Button>
              </div>

              {tasks.length === 0 ? (
                <div className="text-center py-12 border-2 border-dashed rounded-lg bg-muted/30">
                  <p className="text-sm text-muted-foreground mb-2">No tasks added yet.</p>
                  <Button variant="outline" size="sm" onClick={handleAddTask}>Add your first task</Button>
                </div>
              ) : (
                <DragDropContext onDragEnd={onDragEnd}>
                  <Droppable droppableId="tasks">
                    {(provided) => (
                      <div {...provided.droppableProps} ref={provided.innerRef} className="space-y-2">
                        {tasks.map((task, index) => (
                          <Draggable key={task.id} draggableId={task.id} index={index}>
                            {(provided) => (
                              <div ref={provided.innerRef} {...provided.draggableProps} className="flex items-start gap-2 p-3 bg-card border rounded-md shadow-sm group">
                                <div {...provided.dragHandleProps} className="mt-3 text-muted-foreground/40 group-hover:text-muted-foreground cursor-grab">
                                  <GripVertical className="w-5 h-5" />
                                </div>
                                <div className="flex-1 grid grid-cols-1 md:grid-cols-12 gap-3">
                                  <div className="md:col-span-1 flex items-center justify-center">
                                    <div className="w-6 h-6 rounded-full bg-muted text-muted-foreground text-xs flex items-center justify-center font-mono">{index + 1}</div>
                                  </div>
                                  <div className="md:col-span-5">
                                    <Label className="text-xs text-muted-foreground mb-1 block">Task Name *</Label>
                                    <Input placeholder="e.g. Send Welcome Email" value={task.task_name} onChange={e => handleTaskChange(index, 'task_name', e.target.value)} className="h-9 text-sm" />
                                  </div>
                                  <div className="md:col-span-2">
                                    <Label className="text-xs text-muted-foreground mb-1 block">Due In (Days)</Label>
                                    <Input type="number" min="0" value={task.days_until_due} onChange={e => handleTaskChange(index, 'days_until_due', parseInt(e.target.value) || 0)} className="h-9 text-sm" />
                                  </div>
                                  <div className="md:col-span-3">
                                    <Label className="text-xs text-muted-foreground mb-1 block">Priority</Label>
                                    <Select value={task.priority} onValueChange={val => handleTaskChange(index, 'priority', val)}>
                                      <SelectTrigger className="h-9 text-sm"><SelectValue /></SelectTrigger>
                                      <SelectContent>
                                        <SelectItem value="low">Low</SelectItem>
                                        <SelectItem value="medium">Medium</SelectItem>
                                        <SelectItem value="high">High</SelectItem>
                                        <SelectItem value="urgent">Urgent</SelectItem>
                                      </SelectContent>
                                    </Select>
                                  </div>
                                  <div className="md:col-span-1 flex items-end justify-end pb-1">
                                    <Button variant="ghost" size="icon" className="h-8 w-8 text-muted-foreground hover:text-destructive hover:bg-destructive/10" onClick={() => handleRemoveTask(index)}>
                                      <Trash2 className="w-4 h-4" />
                                    </Button>
                                  </div>
                                </div>
                              </div>
                            )}
                          </Draggable>
                        ))}
                        {provided.placeholder}
                      </div>
                    )}
                  </Droppable>
                </DragDropContext>
              )}
            </div>
          </div>
        </div>
        <DialogFooter className="pt-4 border-t">
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={handleSave} disabled={loading} className="gap-2">
            {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
            {editTemplate ? 'Update Template' : 'Save Template'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
