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, Play } from "lucide-react";
import { useWorkflowTemplates } from "@/hooks/useWorkflowTemplates";
import { useAuth } from "@/contexts/AuthContext";
import { toast as sonnerToast } from "sonner";

interface BulkUnit {
  unitId: string;
  unitNumber: string;
  associationId: string;
  associationName: string;
}

interface BulkApplyWorkflowDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  units: BulkUnit[];
  onSuccess?: () => void;
}

export default function BulkApplyWorkflowDialog({ open, onOpenChange, units, onSuccess }: BulkApplyWorkflowDialogProps) {
  const { user } = useAuth();
  const { templates, loading, getTemplates, applyTemplate } = useWorkflowTemplates();
  const [selectedTemplateId, setSelectedTemplateId] = useState("");
  const [description, setDescription] = useState("");
  const [applying, setApplying] = useState(false);
  const [progress, setProgress] = useState(0);

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

  useEffect(() => {
    if (selectedTemplateId) {
      const tmpl = templates.find((t: any) => t.id === selectedTemplateId);
      if (tmpl) {
        setDescription(tmpl.description || "");
      }
    }
  }, [selectedTemplateId, templates]);

  const selectedTemplate = templates.find((t: any) => t.id === selectedTemplateId);

  const handleApply = async () => {
    if (!selectedTemplateId || units.length === 0) return;
    setApplying(true);
    setProgress(0);

    let successCount = 0;
    let failCount = 0;

    for (let i = 0; i < units.length; i++) {
      const unit = units[i];
      const title = `${selectedTemplate?.name || "Workflow"} - Unit ${unit.unitNumber}`;

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

      try {
        const success = await applyTemplate(selectedTemplateId, parentTaskData, unit.unitId);
        if (success) successCount++;
        else failCount++;
      } catch {
        failCount++;
      }
      setProgress(i + 1);
    }

    setApplying(false);

    if (failCount === 0) {
      sonnerToast.success(`Workflow applied to ${successCount} unit(s) successfully`);
    } else {
      sonnerToast.warning(`Applied to ${successCount} unit(s), ${failCount} failed`);
    }

    onOpenChange(false);
    onSuccess?.();
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Play className="h-5 w-5 text-primary" />
            Apply Workflow in Bulk
          </DialogTitle>
          <DialogDescription>
            Apply a workflow template to {units.length} selected unit(s).
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <Label>Workflow Template *</Label>
            <Select value={selectedTemplateId} onValueChange={setSelectedTemplateId} disabled={loading}>
              <SelectTrigger>
                <SelectValue placeholder={loading ? "Loading templates…" : "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>Description (optional)</Label>
            <Textarea value={description} onChange={e => setDescription(e.target.value)} placeholder="Additional notes..." rows={3} />
          </div>
          {applying && (
            <div className="space-y-1">
              <div className="text-xs text-muted-foreground">
                Processing {progress} of {units.length}…
              </div>
              <div className="w-full bg-muted rounded-full h-2">
                <div
                  className="bg-primary h-2 rounded-full transition-all"
                  style={{ width: `${(progress / units.length) * 100}%` }}
                />
              </div>
            </div>
          )}
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={applying}>Cancel</Button>
          <Button onClick={handleApply} disabled={applying || !selectedTemplateId} className="gap-2">
            {applying && <Loader2 className="w-4 h-4 animate-spin" />}
            Apply to {units.length} Unit(s)
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
