import React from "react";
import {
  AlertCircle,
  Check,
  CheckCircle2,
  Clock,
  Loader2,
  Mail,
  Shield,
  User,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Switch } from "@/components/ui/switch";
import type { AiBuilderServiceData } from "./types";

// ---------------------------------------------------------------------------
// ServiceConfigurationModal
// ---------------------------------------------------------------------------

export type ServiceCredentialField = {
  id: string;
  label: string;
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  /** Input type, e.g. "password" for secrets. Defaults to "text". */
  type?: string;
};

export type ServiceConfigurationModalProps = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  serviceTitle: string;
  isConnected: boolean;
  serviceData?: AiBuilderServiceData;
  /** Brand icon node shown in the not-connected centered layout */
  iconNode?: React.ReactNode;
  /** Permissions shown in the not-connected state */
  connectPermissions?: string[];
  /** Subtitle shown below the service name in the not-connected state */
  connectDescription?: string;
  /** Connection detail inputs shown in the not-connected state (e.g. API
   * keys) — the service connects with these instead of an OAuth flow. */
  credentialFields?: ServiceCredentialField[];
  /** Status line shown in the connected state's success banner. */
  connectedStatusLabel?: string;
  /** Label for the connect button in the not-connected state. */
  connectLabel?: string;
  /** Connection-test progress shown above the footer in the not-connected
   * state — drives a spinner (testing), green tick (success) or red error
   * line. The caller owns the test itself. */
  connectStatus?: "idle" | "testing" | "success" | "error";
  connectStatusMessage?: string;
  onConnect: () => void;
  onDisconnect: () => void;
  onReconnect: () => void;
};

export function ServiceConfigurationModal({
  open,
  onOpenChange,
  serviceTitle,
  isConnected,
  serviceData,
  iconNode,
  connectPermissions,
  connectDescription = "Link your account to enable automated workflows with WealthX.",
  credentialFields,
  connectedStatusLabel = "Active — integration is running",
  connectLabel = "Connect",
  connectStatus = "idle",
  connectStatusMessage,
  onConnect,
  onDisconnect,
  onReconnect,
}: ServiceConfigurationModalProps) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="flex max-h-[90vh] flex-col max-w-md">
        {isConnected ? (
          <>
            <DialogHeader>
              <DialogTitle>{serviceTitle}</DialogTitle>
              <DialogDescription>
                Manage your integration settings.
              </DialogDescription>
            </DialogHeader>

            <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto py-2">
              <div className="flex items-center gap-2 px-3 py-2 text-xs font-medium bg-success/10 text-success">
                <CheckCircle2 className="h-3.5 w-3.5 shrink-0" />
                {connectedStatusLabel}
              </div>

              {serviceData && (
                <>
                  <div className="flex flex-col gap-2">
                    <p className="text-overline text-muted-foreground">
                      Account Information
                    </p>
                    <Card className="py-0">
                      <CardContent className="flex flex-col gap-3 p-3">
                        <div className="flex items-center gap-2 text-sm">
                          <User className="text-muted-foreground h-4 w-4 shrink-0" />
                          <span className="text-muted-foreground">
                            {serviceData.accountIdentifierLabel}:
                          </span>
                          <span className="font-medium">
                            {serviceData.accountIdentifier}
                          </span>
                        </div>
                        <div className="flex items-center gap-2 text-sm">
                          <Clock className="text-muted-foreground h-4 w-4 shrink-0" />
                          <span className="text-muted-foreground">
                            Connected on:
                          </span>
                          <span className="font-medium">
                            {serviceData.connectedOn}
                          </span>
                        </div>
                        <div className="flex items-center gap-2 text-sm">
                          <Clock className="text-muted-foreground h-4 w-4 shrink-0" />
                          <span className="text-muted-foreground">
                            Last synced:
                          </span>
                          <span className="font-medium">
                            {serviceData.lastSynced}
                          </span>
                        </div>
                      </CardContent>
                    </Card>
                  </div>

                  <div className="flex flex-col gap-2">
                    <p className="text-overline text-muted-foreground">
                      Granted Permissions
                    </p>
                    <Card className="py-0">
                      <CardContent className="flex flex-col gap-2 p-3">
                        {serviceData.permissions.map((permission) => (
                          <div
                            key={permission}
                            className="flex items-center gap-2 text-sm"
                          >
                            <Shield className="text-success h-4 w-4 shrink-0" />
                            <span>{permission}</span>
                          </div>
                        ))}
                      </CardContent>
                    </Card>
                  </div>

                  <div className="flex flex-col gap-2">
                    <p className="text-overline text-muted-foreground">
                      Sync Settings
                    </p>
                    <Card className="py-0">
                      <CardContent className="flex items-center justify-between gap-3 p-3">
                        <div className="flex flex-col gap-0.5">
                          <p className="text-sm font-medium">
                            {serviceData.syncLabel}
                          </p>
                          <p className="text-muted-foreground text-sm">
                            {serviceData.syncDescription}
                          </p>
                        </div>
                        <Switch
                          checked={serviceData.syncEnabled}
                          onCheckedChange={serviceData.onSyncToggle}
                          aria-label={serviceData.syncLabel}
                        />
                      </CardContent>
                    </Card>
                  </div>

                  {serviceData.emailCategories && (
                    <div className="flex flex-col gap-2">
                      <div>
                        <p className="text-overline text-muted-foreground">
                          Email Filters
                        </p>
                        <p className="text-muted-foreground text-sm mt-0.5">
                          Choose which inbox categories to sync into WealthX.
                        </p>
                      </div>
                      <Card className="py-0">
                        <CardContent className="flex flex-col gap-3 p-3">
                          {serviceData.emailCategories.available.map(
                            (category) => {
                              const checked =
                                serviceData.emailCategories!.selected.includes(
                                  category
                                );
                              return (
                                <div
                                  key={category}
                                  className="flex items-center gap-2"
                                >
                                  <Checkbox
                                    id={`email-cat-${category}`}
                                    checked={checked}
                                    onCheckedChange={(v) => {
                                      const next = v
                                        ? [
                                            ...serviceData.emailCategories!
                                              .selected,
                                            category,
                                          ]
                                        : serviceData.emailCategories!.selected.filter(
                                            (c) => c !== category
                                          );
                                      serviceData.emailCategories!.onChange(
                                        next
                                      );
                                    }}
                                  />
                                  <label
                                    htmlFor={`email-cat-${category}`}
                                    className="text-sm cursor-pointer select-none"
                                  >
                                    {category}
                                  </label>
                                </div>
                              );
                            }
                          )}
                        </CardContent>
                      </Card>
                    </div>
                  )}
                </>
              )}
            </div>

            <DialogFooter>
              <Button
                variant="destructive"
                size="sm"
                onClick={onDisconnect}
                className="mr-auto"
              >
                Disconnect
              </Button>
              <Button
                variant="outline-secondary"
                size="sm"
                onClick={() => onOpenChange(false)}
              >
                Cancel
              </Button>
              <Button size="sm" onClick={onReconnect}>
                Reconnect
              </Button>
            </DialogFooter>
          </>
        ) : (
          <>
            <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto py-2">
              <div className="flex items-center gap-3">
                <div className="flex h-10 w-10 shrink-0 items-center justify-center bg-muted">
                  {iconNode ?? (
                    <Mail className="h-5 w-5 text-muted-foreground" />
                  )}
                </div>
                <div className="flex flex-col gap-0.5">
                  <p className="text-sm font-semibold">
                    Connect {serviceTitle}
                  </p>
                  <p className="text-muted-foreground text-xs">
                    {connectDescription}
                  </p>
                </div>
              </div>

              {credentialFields && credentialFields.length > 0 && (
                <div className="flex flex-col gap-3 border border-border px-4 py-3">
                  <p className="text-overline text-muted-foreground">
                    Connection Details
                  </p>
                  {credentialFields.map((field) => (
                    <div key={field.id} className="flex flex-col gap-1.5">
                      <Label htmlFor={`credential-${field.id}`}>
                        {field.label}
                      </Label>
                      <Input
                        id={`credential-${field.id}`}
                        type={field.type ?? "text"}
                        value={field.value}
                        placeholder={field.placeholder}
                        onChange={(e) => field.onChange(e.target.value)}
                      />
                    </div>
                  ))}
                </div>
              )}

              {connectPermissions && connectPermissions.length > 0 && (
                <div className="flex flex-col gap-2 border border-border px-4 py-3">
                  <p className="text-overline text-muted-foreground">
                    Permissions requested
                  </p>
                  {connectPermissions.map((perm) => (
                    <div key={perm} className="flex items-center gap-2">
                      <Check className="h-3.5 w-3.5 shrink-0 text-success" />
                      <span className="text-sm text-muted-foreground">
                        {perm}
                      </span>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {connectStatus !== "idle" && (
              <div
                className={
                  connectStatus === "error"
                    ? "flex items-center gap-2 px-3 py-2 text-xs font-medium bg-destructive/10 text-destructive"
                    : "flex items-center gap-2 px-3 py-2 text-xs font-medium bg-success/10 text-success"
                }
              >
                {connectStatus === "testing" && (
                  <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" />
                )}
                {connectStatus === "success" && (
                  <CheckCircle2 className="h-3.5 w-3.5 shrink-0" />
                )}
                {connectStatus === "error" && (
                  <AlertCircle className="h-3.5 w-3.5 shrink-0" />
                )}
                {connectStatusMessage ??
                  (connectStatus === "testing"
                    ? "Testing connection..."
                    : connectStatus === "success"
                      ? "Connection valid and live"
                      : "Could not connect. Check your details and try again.")}
              </div>
            )}

            <DialogFooter>
              <Button
                variant="outline-secondary"
                size="sm"
                onClick={() => onOpenChange(false)}
              >
                Cancel
              </Button>
              <Button
                size="sm"
                onClick={onConnect}
                loading={connectStatus === "testing"}
                disabled={connectStatus === "testing"}
              >
                {connectLabel}
              </Button>
            </DialogFooter>
          </>
        )}
      </DialogContent>
    </Dialog>
  );
}
