import { 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 { Loader2 } from "lucide-react";
import { useWorkflowTemplates } from "@/hooks/useWorkflowTemplates";
import { useAuth } from "@/contexts/AuthContext";

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  unitId: string;
  unitNumber: string;
  associationId: string;
  associationName: string;
}

export default function ApplyWorkflowToUnitModal({ open, onOpenChange, unitId, unitNumber, associationId, associationName }: Props) {
  const { user } = useAuth();
  const { templates, loading, getTemplates, applyTemplate } = useWorkflowTemplates();
  const [selectedTemplateId, setSelectedTemplateId] = useState("");
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [applying, setApplying] = useState(false);

  useEffect(() => {
    if (open) {
      getTemplates();
      setSelectedTemplateId("");
      setTitle("");
      setDescription("");
    }
  }, [open, getTemplates]);

  useEffect(() => {
    if (selectedTemplateId) {
      const tmpl = templates.find((t: any) => t.id === selectedTemplateId);
      if (tmpl) {
        setTitle(`${tmpl.name} - Unit ${unitNumber}`);
        setDescription(tmpl.description || "");
      }
    }
  }, [selectedTemplateId, templates, unitNumber]);

  const handleApply = async () => {
    if (!selectedTemplateId || !title.trim()) return;
    setApplying(true);

    const parentTaskData = {
      title,
      description,
      association_id: associationId,
      client_id: associationId,
      created_by: user?.id,
      assigned_to: null,
    };

    const success = await applyTemplate(selectedTemplateId, parentTaskData, unitId);
    setApplying(false);

    if (success) {
      onOpenChange(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Apply Workflow to Unit {unitNumber}</DialogTitle>
          <DialogDescription>
            Select a workflow template to apply to this unit ({associationName}).
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <Label>Workflow Template *</Label>
            <Select value={selectedTemplateId} onValueChange={setSelectedTemplateId}>
              <SelectTrigger><SelectValue placeholder="Select a template" /></SelectTrigger>
              <SelectContent>
                {templates.map((t: any) => (
                  <SelectItem key={t.id} value={t.id}>{t.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <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>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={handleApply} disabled={applying || !selectedTemplateId || !title.trim()}>
            {applying && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
            Start Workflow
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
