import { useState, useEffect } from "react";
import { useToast } from "@/hooks/use-toast";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} 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 { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ColorPicker } from "@/components/ui/color-picker";
import { DashboardConfig } from "./dashboard-layout";
import { generateSnapshot, SnapshotBranding, SnapshotData } from "@/lib/snapshot-utils";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";

interface ShareDashboardDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  dashboard: DashboardConfig;
  dataSources: Array<{
    id: string;
    name: string;
    data: any[];
    fields: Array<{ name: string; type: string }>;
  }>;
}

export function ShareDashboardDialog({
  open,
  onOpenChange,
  dashboard,
  dataSources,
}: ShareDashboardDialogProps) {
  const { toast } = useToast();
  const [activeTab, setActiveTab] = useState<string>("branding");
  const [isSaving, setIsSaving] = useState(false);
  const [isGenerating, setIsGenerating] = useState(false);
  const [snapshotUrl, setSnapshotUrl] = useState<string | null>(null);
  const [branding, setBranding] = useState<SnapshotBranding>({
    logoUrl: "",
    companyName: "",
    title: dashboard.name || "Dashboard Snapshot",
    description: "Dashboard snapshot generated from Active Directory Management",
    primaryColor: "#3f51b5",
    secondaryColor: "#f5f5f5",
    showDate: true,
    showFooter: true,
    footerText: "© " + new Date().getFullYear() + " - Generated by Active Directory Management",
    expiresInDays: 30,
  });

  // Reset the snapshot URL when the dialog is opened
  useEffect(() => {
    if (open) {
      setSnapshotUrl(null);
      setActiveTab("branding");
    }
  }, [open]);

  // Update title when dashboard name changes
  useEffect(() => {
    if (dashboard.name) {
      setBranding(prev => ({ ...prev, title: dashboard.name }));
    }
  }, [dashboard.name]);

  const handleBrandingChange = (key: keyof SnapshotBranding, value: any) => {
    setBranding((prev) => ({
      ...prev,
      [key]: value,
    }));
  };

  const generateDashboardSnapshot = async () => {
    try {
      setIsGenerating(true);
      
      // Here you would normally make an API call to store the snapshot
      // For now, we'll just simulate it
      
      const snapshotData: SnapshotData = generateSnapshot({
        dashboard,
        dataSources,
        branding,
      });
      
      // Mock API call - in production this would save to server and return a URL
      await new Promise((resolve) => setTimeout(resolve, 1500));
      
      // Simulate a returned URL
      const mockSnapshotId = `snapshot-${Date.now().toString(36)}`;
      const url = `${window.location.origin}/snapshot/${mockSnapshotId}`;
      
      setSnapshotUrl(url);
      setActiveTab("share");
      
      toast({
        title: "Snapshot Generated",
        description: "Your dashboard snapshot has been created successfully.",
      });
    } catch (error) {
      console.error("Error generating snapshot:", error);
      toast({
        title: "Error",
        description: "Failed to generate dashboard snapshot. Please try again.",
        variant: "destructive",
      });
    } finally {
      setIsGenerating(false);
    }
  };

  const copyToClipboard = async () => {
    if (!snapshotUrl) return;
    
    try {
      await navigator.clipboard.writeText(snapshotUrl);
      toast({
        title: "Copied to Clipboard",
        description: "Snapshot URL has been copied to your clipboard.",
      });
    } catch (error) {
      console.error("Error copying to clipboard:", error);
      toast({
        title: "Error",
        description: "Failed to copy URL to clipboard. Please try manually.",
        variant: "destructive",
      });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[700px] max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Share Dashboard: {dashboard.name}</DialogTitle>
          <DialogDescription>
            Create a shareable snapshot of your dashboard with custom branding.
          </DialogDescription>
        </DialogHeader>

        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="branding">Branding</TabsTrigger>
            <TabsTrigger value="share" disabled={!snapshotUrl}>Share</TabsTrigger>
          </TabsList>

          {/* Branding Tab */}
          <TabsContent value="branding" className="space-y-4 py-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="companyName">Company Name</Label>
                  <Input
                    id="companyName"
                    value={branding.companyName}
                    onChange={(e) => handleBrandingChange("companyName", e.target.value)}
                    placeholder="Enter your company name"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="logoUrl">Logo URL</Label>
                  <Input
                    id="logoUrl"
                    value={branding.logoUrl}
                    onChange={(e) => handleBrandingChange("logoUrl", e.target.value)}
                    placeholder="https://example.com/logo.png"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="title">Dashboard Title</Label>
                  <Input
                    id="title"
                    value={branding.title}
                    onChange={(e) => handleBrandingChange("title", e.target.value)}
                    placeholder="Dashboard Title"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="description">Description</Label>
                  <Textarea
                    id="description"
                    value={branding.description}
                    onChange={(e) => handleBrandingChange("description", e.target.value)}
                    placeholder="Brief description of this dashboard"
                    rows={3}
                  />
                </div>
              </div>

              <div className="space-y-4">
                <div className="space-y-2">
                  <Label>Primary Color</Label>
                  <div className="flex items-center gap-2">
                    <ColorPicker
                      value={branding.primaryColor}
                      onChange={(color) => handleBrandingChange("primaryColor", color)}
                    />
                    <Input
                      value={branding.primaryColor}
                      onChange={(e) => handleBrandingChange("primaryColor", e.target.value)}
                      className="flex-1"
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label>Secondary Color</Label>
                  <div className="flex items-center gap-2">
                    <ColorPicker
                      value={branding.secondaryColor}
                      onChange={(color) => handleBrandingChange("secondaryColor", color)}
                    />
                    <Input
                      value={branding.secondaryColor}
                      onChange={(e) => handleBrandingChange("secondaryColor", e.target.value)}
                      className="flex-1"
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="expiresInDays">Expires In</Label>
                  <Select
                    value={branding.expiresInDays.toString()}
                    onValueChange={(value) => handleBrandingChange("expiresInDays", parseInt(value))}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select expiration period" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="0">Never Expires</SelectItem>
                      <SelectItem value="1">1 Day</SelectItem>
                      <SelectItem value="7">7 Days</SelectItem>
                      <SelectItem value="30">30 Days</SelectItem>
                      <SelectItem value="90">90 Days</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="flex items-center space-x-2 pt-4">
                  <Switch
                    id="showDate"
                    checked={branding.showDate}
                    onCheckedChange={(checked) => handleBrandingChange("showDate", checked)}
                  />
                  <Label htmlFor="showDate">Show Date</Label>
                </div>

                <div className="flex items-center space-x-2">
                  <Switch
                    id="showFooter"
                    checked={branding.showFooter}
                    onCheckedChange={(checked) => handleBrandingChange("showFooter", checked)}
                  />
                  <Label htmlFor="showFooter">Show Footer</Label>
                </div>

                {branding.showFooter && (
                  <div className="space-y-2">
                    <Label htmlFor="footerText">Footer Text</Label>
                    <Input
                      id="footerText"
                      value={branding.footerText}
                      onChange={(e) => handleBrandingChange("footerText", e.target.value)}
                      placeholder="Footer Text"
                    />
                  </div>
                )}
              </div>
            </div>
          </TabsContent>

          {/* Share Tab */}
          <TabsContent value="share" className="space-y-4 py-4">
            {snapshotUrl && (
              <div className="space-y-4">
                <div className="p-4 border rounded-md bg-secondary">
                  <p className="font-medium mb-2">Snapshot URL:</p>
                  <div className="flex items-center gap-2">
                    <Input value={snapshotUrl} readOnly />
                    <Button onClick={copyToClipboard} className="shrink-0">
                      Copy
                    </Button>
                  </div>
                </div>

                <div className="space-y-2">
                  <p className="text-sm text-muted-foreground">
                    Share this URL to give access to this dashboard snapshot.
                    {branding.expiresInDays > 0
                      ? ` This link will expire in ${branding.expiresInDays} days.`
                      : " This link will never expire."}
                  </p>
                </div>
              </div>
            )}
          </TabsContent>
        </Tabs>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          {activeTab === "branding" ? (
            <Button 
              onClick={generateDashboardSnapshot} 
              disabled={isGenerating}
            >
              {isGenerating ? "Generating..." : "Generate Snapshot"}
            </Button>
          ) : (
            <Button 
              onClick={() => {
                setActiveTab("branding");
                setSnapshotUrl(null);
              }}
            >
              Create New Snapshot
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}