"use client";

import { useState } from "react";
import { Plus, RefreshCw, Layers, CheckCircle2, AlertTriangle, FileCode } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input, Label, Select } from "@/components/ui/input";
import { Card, CardBody } from "@/components/ui/card";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { cn } from "@/lib/utils";

type Flow = {
  id: string;
  metaFlowId: string;
  name: string;
  status: string;
  categories: any;
  validationErrors: any;
  updatedAt: Date;
};

export function FlowsClient({ initialFlows, accountId }: { initialFlows: Flow[]; accountId: string }) {
  const [syncing, setSyncing] = useState(false);
  const [creating, setCreating] = useState(false);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const router = useRouter();

  async function handleDelete(flowId: string) {
    if (!confirm("Are you sure you want to delete this flow? This action cannot be undone.")) return;
    try {
      const res = await fetch(`/api/flows/${flowId}`, {
        method: "DELETE",
      });
      if (!res.ok) {
        const json = await res.json();
        toast.error(json.error || "Failed to delete flow.");
      } else {
        toast.success("Flow deleted successfully.");
        router.refresh();
      }
    } catch (err) {
      toast.error("Failed to connect to server.");
    }
  }

  async function handleSync() {
    setSyncing(true);
    try {
      const res = await fetch(`/api/flows/sync?accountId=${accountId}`, {
        method: "POST",
      });
      const json = await res.json();
      if (!res.ok) {
        toast.error(json.error || "Failed to sync flows.");
      } else {
        toast.success(`Successfully synced ${json.count} flows.`);
        router.refresh();
      }
    } catch (e) {
      toast.error("Failed to connect to server.");
    } finally {
      setSyncing(false);
    }
  }

  async function handleCreateFlow(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setCreating(true);
    const formData = new FormData(e.currentTarget);
    const name = formData.get("name") as string;
    const category = formData.get("category") as string;

    try {
      const res = await fetch(`/api/flows/create`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          accountId,
          name,
          categories: [category],
        }),
      });
      const json = await res.json();
      if (!res.ok) {
        toast.error(json.error || "Failed to create flow.");
      } else {
        toast.success("Flow created successfully!");
        setShowCreateModal(false);
        router.refresh();
      }
    } catch (err) {
      toast.error("Failed to connect to server.");
    } finally {
      setCreating(false);
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-foreground">WhatsApp Flows</h1>
          <p className="text-sm text-muted-foreground mt-1">
            Build and manage interactive forms and experiences for your customers.
          </p>
        </div>
        <div className="flex items-center gap-3">
          <Button variant="outline" onClick={handleSync} disabled={syncing}>
            {syncing ? (
              <RefreshCw className="mr-2 h-4 w-4 animate-spin text-muted-foreground" />
            ) : (
              <RefreshCw className="mr-2 h-4 w-4 text-muted-foreground" />
            )}
            Sync with Meta Flow
          </Button>
          <Button onClick={() => setShowCreateModal(true)}>
            <Plus className="mr-2 h-4 w-4" />
            Create Flow
          </Button>
        </div>
      </div>

      {initialFlows.length === 0 ? (
        <Card className="mt-8">
          <CardBody className="flex flex-col items-center justify-center py-20 text-center">
            <div className="flex h-12 w-12 items-center justify-center rounded-full bg-indigo-100 text-indigo-600 mb-4">
              <Layers className="h-6 w-6" />
            </div>
            <h3 className="text-lg font-medium text-foreground">No flows found</h3>
            <p className="mt-1 max-w-sm text-sm text-muted-foreground">
              Get started by creating a new WhatsApp Flow or syncing your existing flows from Meta.
            </p>
            <div className="mt-6">
              <Button onClick={() => setShowCreateModal(true)}>
                <Plus className="mr-2 h-4 w-4" />
                Create Flow
              </Button>
            </div>
          </CardBody>
        </Card>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 mt-6">
          {initialFlows.map((flow) => {
            const hasErrors = flow.validationErrors && Array.isArray(flow.validationErrors) && flow.validationErrors.length > 0;
            return (
              <Card key={flow.id} className="relative overflow-hidden group hover:shadow-md transition-shadow">
                <CardBody className="p-5">
                  <div className="flex items-start justify-between">
                    <div className="flex items-center gap-2">
                      <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-indigo-50 text-indigo-600">
                        <FileCode className="h-5 w-5" />
                      </div>
                      <div>
                        <h3 className="font-semibold text-foreground truncate max-w-[150px]">{flow.name}</h3>
                        <p className="text-xs text-muted-foreground font-mono mt-0.5">ID: {flow.metaFlowId}</p>
                      </div>
                    </div>
                  </div>
                  
                  <div className="mt-4 flex items-center gap-2 flex-wrap">
                    <span className={cn(
                      "inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium",
                      flow.status === "PUBLISHED" ? "bg-emerald-50 text-emerald-700" : "bg-amber-50 text-amber-700"
                    )}>
                      {flow.status === "PUBLISHED" && <CheckCircle2 className="mr-1 h-3 w-3" />}
                      {flow.status}
                    </span>
                    
                    {hasErrors && (
                      <span className="inline-flex items-center rounded-full bg-red-50 px-2 py-0.5 text-xs font-medium text-red-700">
                        <AlertTriangle className="mr-1 h-3 w-3" />
                        Errors
                      </span>
                    )}

                    {Array.isArray(flow.categories) && flow.categories.map((cat: string, i: number) => (
                      <span key={i} className="inline-flex items-center rounded-full bg-muted dark:bg-zinc-800 px-2 py-0.5 text-xs font-medium text-muted-foreground dark:text-muted-foreground">
                        {cat}
                      </span>
                    ))}
                  </div>

                  <div className="mt-4 pt-4 border-t border-border flex items-center justify-between text-xs text-muted-foreground">
                    <span suppressHydrationWarning>Updated {new Date(flow.updatedAt).toLocaleDateString()}</span>
                    <div className="flex items-center gap-4">
                      <button onClick={() => handleDelete(flow.id)} className="text-red-500 font-medium hover:underline">
                        Delete
                      </button>
                      <Link href={`/flows/${flow.id}/builder`} className="text-indigo-600 font-medium hover:underline">
                        Edit Flow
                      </Link>
                    </div>
                  </div>
                </CardBody>
              </Card>
            );
          })}
        </div>
      )}

      {showCreateModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-zinc-900/40 p-4">
          <div className="w-full max-w-md rounded-2xl bg-card p-6 shadow-xl">
            <h2 className="text-lg font-semibold text-foreground">Create WhatsApp Flow</h2>
            <form className="mt-4 space-y-4" onSubmit={handleCreateFlow}>
              <div>
                <Label>Flow Name</Label>
                <Input name="name" required placeholder="e.g. Lead Generation Form" />
                <p className="text-[10px] text-muted-foreground mt-1">Must be unique within your WhatsApp Business Account.</p>
              </div>
              <div>
                <Label>Category</Label>
                <Select name="category" required>
                  <option value="LEAD_GENERATION">Lead Generation</option>
                  <option value="CUSTOMER_SUPPORT">Customer Support</option>
                  <option value="SURVEY">Survey</option>
                  <option value="APPOINTMENT_BOOKING">Appointment Booking</option>
                  <option value="OTHER">Other</option>
                </Select>
              </div>
              
              <div className="flex justify-end gap-2 pt-2">
                <Button type="button" variant="ghost" onClick={() => setShowCreateModal(false)} disabled={creating}>
                  Cancel
                </Button>
                <Button type="submit" disabled={creating}>
                  {creating ? "Creating..." : "Create Flow"}
                </Button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
