import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { supabase } from '@/integrations/supabase/client';
import { useWorkflowTemplates } from '@/hooks/useWorkflowTemplates';
import { useAuth } from '@/contexts/AuthContext';
import { Loader2 } from 'lucide-react';

export default function ApplyTemplateModal({ open, onOpenChange, template, onSuccess }) {
  const { user } = useAuth();
  const { applyTemplate, loading } = useWorkflowTemplates();
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [associationId, setAssociationId] = useState('');
  const [associations, setAssociations] = useState([]);

  useEffect(() => {
    if (open) {
      setTitle(template?.name || '');
      setDescription(template?.description || '');
      supabase.from('associations').select('id, name').eq('status', 'active').order('name').then(({ data }) => setAssociations(data || []));
    }
  }, [open, template]);

  const handleApply = async () => {
    if (!title.trim()) return;
    const parentTaskData = {
      title,
      description,
      association_id: associationId || null,
      client_id: associationId || null,
      created_by: user?.id,
      assigned_to: null,
    };
    const success = await applyTemplate(template.id, parentTaskData);
    if (success) {
      onOpenChange(false);
      if (onSuccess) onSuccess();
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Start Workflow</DialogTitle>
          <DialogDescription>Apply the "{template?.name}" template to create a new workflow.</DialogDescription>
        </DialogHeader>
        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <Label>Workflow Title *</Label>
            <Input value={title} onChange={e => setTitle(e.target.value)} placeholder="Workflow name" />
          </div>
          <div className="space-y-2">
            <Label>Description</Label>
            <Textarea value={description} onChange={e => setDescription(e.target.value)} placeholder="Additional notes..." rows={3} />
          </div>
          <div className="space-y-2">
            <Label>Client (Optional)</Label>
            <Select value={associationId} onValueChange={setAssociationId}>
              <SelectTrigger><SelectValue placeholder="Select client" /></SelectTrigger>
              <SelectContent>
                {associations.map(a => (<SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>))}
              </SelectContent>
            </Select>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={handleApply} disabled={loading || !title.trim()}>
            {loading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
            Start Workflow
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
