"use client";

import { useEffect, useState } from "react";
import {
  Cable,
  Loader2,
  AlertCircle,
  Settings,
  Globe,
  RefreshCw,
  Zap,
  Building,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  Pencil,
  Save,
  X,
  FileText,
  ListOrdered,
} from "lucide-react";
import { toast } from "sonner";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { useT } from "@/shared/i18n/client";
import { Badge } from "@/presentation/components/ui/badge";
import { Button } from "@/presentation/components/ui/button";
import { Input } from "@/presentation/components/ui/input";
import { Textarea } from "@/presentation/components/ui/textarea";
import { Switch } from "@/presentation/components/ui/switch";
import { env } from "@/infrastructure/config/env";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
} from "@/presentation/components/ui/sheet";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/presentation/components/ui/select";
import type { UpdateIntegrationPayload } from "@/domain/entities/integration";

const CATEGORIES = [
  "fuel_cards",
  "telepeage",
  "electric_recharge",
  "accounting",
  "leasing_companies",
  "telematics",
  "insurance",
  "payroll",
  "expenses",
];

const CONNECTION_METHODS = ["sftp", "manual", "api", "oauth"];
const SYNC_FREQUENCIES = ["real_time", "hourly", "daily", "weekly"];
const ACTIVATION_MODES = ["immediate", "on_request"];

const VALID_MODULES = [
  "Carburant",
  "Dépenses",
  "Véhicules",
  "Télépéage",
  "Péage",
  "Énergie",
  "Entretien",
  "Contrats",
  "Géolocalisation",
  "Conduite",
  "Sinistres",
  "Comptabilité",
  "Collaborateurs",
];

interface Props {
  integrationId: number | null;
  onClose: () => void;
  onChanged?: () => void;
}

export function IntegrationDetailSheet({
  integrationId,
  onClose,
  onChanged,
}: Props) {
  const t = useT();
  const container = useRepositories();
  const d = t.pages.integrations.detail;

  const [isEditing, setIsEditing] = useState(false);
  const [saving, setSaving] = useState(false);
  const [formData, setFormData] = useState<UpdateIntegrationPayload>({});

  const { data: integration, loading, error, refetch } = useApiQuery(
    () => container.integrationRepository.findById(integrationId as number),
    { enabled: integrationId !== null, deps: [integrationId] }
  );

  // Initialize form data when entering edit mode or integration changes
  useEffect(() => {
    if (integration) {
      setFormData({
        name: integration.name,
        category: integration.category,
        description: integration.description || "",
        connection_method: integration.connection_method,
        sync_frequency: integration.sync_frequency || null,
        activation_mode: integration.activation_mode,
        requirements: integration.requirements || "",
        modules: integration.modules || [],
      });
    }
  }, [integration, isEditing]);

  const handleToggleEnabled = async (checked: boolean) => {
    if (!integration) return;
    try {
      await container.integrationRepository.update(integration.id, {
        enabled: checked,
      });
      toast.success(checked ? d.toasts.enabled : d.toasts.disabled);
      refetch();
      onChanged?.();
    } catch (err) {
      toast.error(d.toasts.error);
    }
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!integration) return;
    setSaving(true);
    try {
      await container.integrationRepository.update(integration.id, formData);
      toast.success(d.toasts.updated);
      setIsEditing(false);
      refetch();
      onChanged?.();
    } catch (err) {
      toast.error(d.toasts.error);
    } finally {
      setSaving(false);
    }
  };

  const handleToggleModule = (mod: string) => {
    const current = formData.modules || [];
    if (current.includes(mod)) {
      setFormData((prev) => ({
        ...prev,
        modules: current.filter((m) => m !== mod),
      }));
    } else {
      setFormData((prev) => ({
        ...prev,
        modules: [...current, mod],
      }));
    }
  };

  return (
    <Sheet
      open={integrationId !== null}
      onOpenChange={(open) => {
        if (!open) {
          setIsEditing(false);
          onClose();
        }
      }}
    >
      <SheetContent className="sm:max-w-xl w-[550px] overflow-y-auto flex flex-col h-full border-l border-border bg-card p-0">
        <SheetHeader className="border-b border-border p-6 pb-4">
          <SheetTitle className="flex items-center gap-3">
            <Cable className="w-5 h-5 text-primary" />
            <span>{isEditing ? d.editTitle : d.title}</span>
          </SheetTitle>
        </SheetHeader>

        {loading ? (
          <div className="flex-1 flex items-center justify-center">
            <Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
          </div>
        ) : error ? (
          <div className="flex-1 flex flex-col items-center justify-center p-6 text-center">
            <AlertCircle className="w-8 h-8 text-destructive mb-3" />
            <p className="text-sm font-semibold text-destructive">{error}</p>
            <Button variant="outline" size="sm" onClick={refetch} className="mt-4">
              {t.common.retry}
            </Button>
          </div>
        ) : integration ? (
          <div className="flex-1 flex flex-col justify-between overflow-hidden">
            {/* Scrollable Content */}
            <div className="flex-1 overflow-y-auto p-6 space-y-6">
              {/* Header card details */}
              <div className="bg-muted/40 border border-border/80 rounded-xl p-4 flex items-start gap-4">
                <div className="w-14 h-14 rounded-lg bg-background flex items-center justify-center border border-border shrink-0 overflow-hidden shadow-sm">
                  {integration.logo ? (
                    <img
                      src={`${env.backendOrigin}/${integration.logo}`}
                      alt={integration.name}
                      className="w-full h-full object-contain p-1.5"
                    />
                  ) : (
                    <Cable className="w-6 h-6 text-muted-foreground" />
                  )}
                </div>
                <div className="min-w-0 flex-1">
                  <h3 className="text-base font-bold text-foreground truncate">
                    {integration.name}
                  </h3>
                  <div className="mt-2 flex items-center justify-between">
                    <span className="text-xs text-muted-foreground font-medium">
                      {d.fields.status}
                    </span>
                    <div className="flex items-center gap-2">
                      <span className="text-xs font-semibold">
                        {integration.enabled
                          ? t.pages.integrations.statusLabels.enabled
                          : t.pages.integrations.statusLabels.disabled}
                      </span>
                      <Switch
                        checked={integration.enabled}
                        onCheckedChange={handleToggleEnabled}
                        disabled={saving}
                      />
                    </div>
                  </div>
                </div>
              </div>

              {isEditing ? (
                /* Edit Form Mode */
                <form onSubmit={handleSave} className="space-y-4">
                  {/* Name field */}
                  <div className="space-y-1.5">
                    <label className="text-xs font-semibold text-muted-foreground">
                      {d.fields.name}
                    </label>
                    <Input
                      value={formData.name || ""}
                      onChange={(e) =>
                        setFormData((prev) => ({ ...prev, name: e.target.value }))
                      }
                      required
                    />
                  </div>

                  {/* Code field */}
                  <div className="space-y-1.5">
                    <label className="text-xs font-semibold text-muted-foreground">
                      {d.fields.code}
                    </label>
                    <Input
                      value={integration.code}
                      disabled
                    />
                  </div>

                  {/* Category field */}
                  <div className="space-y-1.5">
                    <label className="text-xs font-semibold text-muted-foreground">
                      {d.fields.category}
                    </label>
                    <Select
                      value={formData.category}
                      onValueChange={(v) =>
                        setFormData((prev) => ({ ...prev, category: v }))
                      }
                    >
                      <SelectTrigger className="w-full">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {CATEGORIES.map((c) => (
                          <SelectItem key={c} value={c}>
                            {t.pages.integrations.categories[c] ?? c}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  {/* Connection Method */}
                  <div className="space-y-1.5">
                    <label className="text-xs font-semibold text-muted-foreground">
                      {d.fields.connectionMethod}
                    </label>
                    <Select
                      value={formData.connection_method}
                      onValueChange={(v) =>
                        setFormData((prev) => ({
                          ...prev,
                          connection_method: v as any,
                        }))
                      }
                    >
                      <SelectTrigger className="w-full">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {CONNECTION_METHODS.map((m) => (
                          <SelectItem key={m} value={m}>
                            {t.pages.integrations.connectionMethodLabels[m] ?? m}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  {/* Sync Frequency */}
                  <div className="space-y-1.5">
                    <label className="text-xs font-semibold text-muted-foreground">
                      {d.fields.syncFrequency}
                    </label>
                    <Select
                      value={formData.sync_frequency || "none"}
                      onValueChange={(v) =>
                        setFormData((prev) => ({
                          ...prev,
                          sync_frequency: v === "none" ? null : (v as any),
                        }))
                      }
                    >
                      <SelectTrigger className="w-full">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="none">{t.common.none}</SelectItem>
                        {SYNC_FREQUENCIES.map((f) => (
                          <SelectItem key={f} value={f}>
                            {d.syncFrequencies[f] ?? f}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  {/* Activation Mode */}
                  <div className="space-y-1.5">
                    <label className="text-xs font-semibold text-muted-foreground">
                      {d.fields.activationMode}
                    </label>
                    <Select
                      value={formData.activation_mode}
                      onValueChange={(v) =>
                        setFormData((prev) => ({
                          ...prev,
                          activation_mode: v as any,
                        }))
                      }
                    >
                      <SelectTrigger className="w-full">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {ACTIVATION_MODES.map((m) => (
                          <SelectItem key={m} value={m}>
                            {d.activationModes[m] ?? m}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  {/* Description field */}
                  <div className="space-y-1.5">
                    <label className="text-xs font-semibold text-muted-foreground">
                      {d.fields.description}
                    </label>
                    <Textarea
                      rows={3}
                      value={formData.description || ""}
                      onChange={(e) =>
                        setFormData((prev) => ({
                          ...prev,
                          description: e.target.value,
                        }))
                      }
                    />
                  </div>

                  {/* Requirements field */}
                  <div className="space-y-1.5">
                    <label className="text-xs font-semibold text-muted-foreground">
                      {d.requirements}
                    </label>
                    <Textarea
                      rows={3}
                      value={formData.requirements || ""}
                      onChange={(e) =>
                        setFormData((prev) => ({
                          ...prev,
                          requirements: e.target.value,
                        }))
                      }
                    />
                  </div>

                  {/* Modules field */}
                  <div className="space-y-1.5">
                    <label className="text-xs font-semibold text-muted-foreground">
                      {d.fields.modules}
                    </label>
                    <div className="flex flex-wrap gap-1.5 mt-1">
                      {VALID_MODULES.map((mod) => {
                        const isSelected = (formData.modules || []).includes(mod);
                        return (
                          <Badge
                            key={mod}
                            variant={isSelected ? "default" : "outline"}
                            className={`cursor-pointer transition-colors text-[11px] py-1 px-2.5 select-none ${
                              isSelected
                                ? "bg-primary text-primary-foreground hover:bg-primary/90"
                                : "bg-background text-muted-foreground border-border hover:bg-muted hover:text-foreground"
                            }`}
                            onClick={() => handleToggleModule(mod)}
                          >
                            {mod}
                          </Badge>
                        );
                      })}
                    </div>
                  </div>
                </form>
              ) : (
                /* Read-Only Details View */
                <div className="space-y-5">
                  {/* General Info block */}
                  <div className="space-y-3">
                    <h4 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                      {d.generalInfo}
                    </h4>
                    <div className="border border-border rounded-xl divide-y divide-border/60 overflow-hidden bg-background">
                      <div className="flex justify-between items-center px-4 py-2.5">
                        <span className="text-xs text-muted-foreground">
                          {d.fields.category}
                        </span>
                        <span className="text-xs font-semibold bg-muted px-2 py-0.5 rounded text-foreground">
                          {t.pages.integrations.categories[integration.category] ??
                            integration.category}
                        </span>
                      </div>
                      <div className="flex justify-between items-center px-4 py-2.5">
                        <span className="text-xs text-muted-foreground">
                          {d.fields.connectionMethod}
                        </span>
                        <span className="text-xs font-medium text-foreground capitalize">
                          {t.pages.integrations.connectionMethodLabels[
                            integration.connection_method
                          ] ?? integration.connection_method}
                        </span>
                      </div>
                      <div className="flex justify-between items-center px-4 py-2.5">
                        <span className="text-xs text-muted-foreground">
                          {d.fields.syncFrequency}
                        </span>
                        <span className="text-xs font-medium text-foreground">
                          {integration.sync_frequency
                            ? d.syncFrequencies[integration.sync_frequency] ??
                            integration.sync_frequency
                            : "—"}
                        </span>
                      </div>
                      <div className="flex justify-between items-center px-4 py-2.5">
                        <span className="text-xs text-muted-foreground">
                          {d.fields.activationMode}
                        </span>
                        <span className="text-xs font-medium text-foreground">
                          {d.activationModes[integration.activation_mode] ??
                            integration.activation_mode}
                        </span>
                      </div>
                    </div>
                  </div>

                  {/* Description block */}
                  {integration.description && (
                    <div className="space-y-2">
                      <h4 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
                        <FileText className="w-3.5 h-3.5" />
                        {d.fields.description}
                      </h4>
                      <p className="text-xs text-foreground bg-muted/20 border border-border/60 rounded-xl p-3.5 leading-relaxed whitespace-pre-line">
                        {integration.description}
                      </p>
                    </div>
                  )}

                  {/* Supported Modules */}
                  <div className="space-y-2">
                    <h4 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
                      <Settings className="w-3.5 h-3.5" />
                      {d.supportedModules}
                    </h4>
                    {integration.modules && integration.modules.length > 0 ? (
                      <div className="flex flex-wrap gap-1.5">
                        {integration.modules.map((m) => (
                          <Badge
                            key={m}
                            variant="secondary"
                            className="text-[10px] py-0.5 px-2 bg-primary/10 text-primary border-transparent font-medium"
                          >
                            {m}
                          </Badge>
                        ))}
                      </div>
                    ) : (
                      <p className="text-xs text-muted-foreground italic pl-1">
                        {d.noModules}
                      </p>
                    )}
                  </div>

                  {/* Requirements block */}
                  <div className="space-y-2">
                    <h4 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
                      <AlertTriangle className="w-3.5 h-3.5 text-amber-500" />
                      {d.requirements}
                    </h4>
                    {integration.requirements ? (
                      <p className="text-xs text-foreground bg-amber-50/50 dark:bg-amber-950/10 border border-amber-200/50 rounded-xl p-3.5 leading-relaxed whitespace-pre-line">
                        {integration.requirements}
                      </p>
                    ) : (
                      <p className="text-xs text-muted-foreground italic pl-1">
                        {d.noRequirements}
                      </p>
                    )}
                  </div>

                  {/* Activation Steps block */}
                  <div className="space-y-2">
                    <h4 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
                      <ListOrdered className="w-3.5 h-3.5 text-primary" />
                      {d.activationSteps}
                    </h4>
                    {integration.activation_steps &&
                      integration.activation_steps.length > 0 ? (
                      <ol className="space-y-2 bg-muted/20 border border-border/60 rounded-xl p-3.5 list-decimal pl-7 text-xs leading-relaxed text-foreground">
                        {integration.activation_steps.map((step, idx) => (
                          <li key={idx} className="pl-1">
                            {step}
                          </li>
                        ))}
                      </ol>
                    ) : (
                      <p className="text-xs text-muted-foreground italic pl-1">
                        {d.noActivationSteps}
                      </p>
                    )}
                  </div>

                  {/* Active Connections block */}
                  <div className="space-y-2">
                    <h4 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
                      <Building className="w-3.5 h-3.5" />
                      {d.activeConnections}
                    </h4>
                    {integration.integration_connections &&
                      integration.integration_connections.length > 0 ? (
                      <div className="border border-border/80 rounded-xl overflow-hidden bg-background divide-y divide-border/60">
                        {integration.integration_connections.map((conn) => (
                          <div
                            key={conn.id}
                            className="flex items-center justify-between p-3.5 text-xs"
                          >
                            <div className="min-w-0 flex-1">
                              <p className="font-semibold text-foreground truncate">
                                {conn.company?.name || `Company ID: ${conn.company_id}`}
                              </p>
                              <p className="text-[10px] text-muted-foreground mt-0.5">
                                {conn.connected_at
                                  ? `${new Date(conn.connected_at).toLocaleDateString()}`
                                  : d.noConnectionDate}
                              </p>
                            </div>
                            <div className="flex items-center gap-3">
                              {/* Status Badge for Connection */}
                              <Badge
                                variant="outline"
                                className={`text-[9px] font-bold px-1.5 py-0 border transition-colors capitalize ${conn.status === "active"
                                    ? "bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-500/10 dark:text-emerald-400"
                                    : "bg-red-50 text-red-700 border-red-200 dark:bg-red-500/10 dark:text-red-400"
                                  }`}
                              >
                                {conn.status}
                              </Badge>
                            </div>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <p className="text-xs text-muted-foreground italic pl-1">
                        {d.noConnections}
                      </p>
                    )}
                  </div>
                </div>
              )}
            </div>

            {/* Footer actions */}
            <div className="border-t border-border p-4 bg-muted/30 flex items-center justify-end gap-2 shrink-0">
              {isEditing ? (
                <>
                  <Button
                    variant="outline"
                    onClick={() => setIsEditing(false)}
                    disabled={saving}
                    className="h-9 text-xs"
                  >
                    <X className="w-3.5 h-3.5 mr-2" />
                    {d.actions.cancel}
                  </Button>
                  <Button onClick={handleSave} disabled={saving} className="h-9 text-xs">
                    {saving ? (
                      <>
                        <Loader2 className="w-3.5 h-3.5 mr-2 animate-spin" />
                        {d.actions.saving}
                      </>
                    ) : (
                      <>
                        <Save className="w-3.5 h-3.5 mr-2" />
                        {d.actions.save}
                      </>
                    )}
                  </Button>
                </>
              ) : (
                <>
                  <Button
                    variant="outline"
                    onClick={() => setIsEditing(true)}
                    className="h-9 text-xs"
                  >
                    <Pencil className="w-3.5 h-3.5 mr-2" />
                    {d.actions.edit}
                  </Button>
                  <Button variant="secondary" onClick={onClose} className="h-9 text-xs">
                    {t.common.cancel}
                  </Button>
                </>
              )}
            </div>
          </div>
        ) : null}
      </SheetContent>
    </Sheet>
  );
}
