import * as React from "react";
import { CheckIcon, CopyIcon } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Spinner } from "@/components/ui/spinner";
import { Textarea } from "@/components/ui/textarea";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { cn } from "@/lib/utils";

// ---------------------------------------------------------------------------
// Shared helper
// ---------------------------------------------------------------------------

function Field({
  id,
  label,
  required,
  children,
}: {
  id?: string;
  label: string;
  required?: boolean;
  children: React.ReactNode;
}) {
  return (
    <div className="flex flex-col gap-1.5">
      <Label htmlFor={id}>
        {label}
        {required && <span className="ml-0.5 text-destructive">*</span>}
      </Label>
      {children}
    </div>
  );
}

// ---------------------------------------------------------------------------
// ShareDetailsDialog
// ---------------------------------------------------------------------------

export interface ShareDetailsDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  contactName: string;
  /** Pre-generated share link to copy. */
  shareUrl: string;
  /** When provided, shows an "Email link" button that calls this handler. */
  onEmailLink?: () => void;
  isSendingEmail?: boolean;
  className?: string;
}

export function ShareDetailsDialog({
  open,
  onOpenChange,
  contactName,
  shareUrl,
  onEmailLink,
  isSendingEmail = false,
  className,
}: ShareDetailsDialogProps) {
  const [copied, setCopied] = React.useState(false);

  function handleCopy() {
    navigator.clipboard.writeText(shareUrl).catch(() => {});
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent size="md" className={className}>
        <DialogHeader>
          <DialogTitle>Share Client Details</DialogTitle>
        </DialogHeader>

        <p className="text-sm text-muted-foreground">
          Share a secure link to{" "}
          <span className="font-medium text-foreground">{contactName}</span>'s
          financial summary report.
        </p>

        <Field label="Shareable link">
          <div className="flex gap-2">
            <Input
              readOnly
              value={shareUrl}
              className="flex-1 font-mono text-xs text-muted-foreground"
              onClick={(e) => (e.target as HTMLInputElement).select()}
            />
            <Button
              variant="outline"
              size="icon"
              onClick={handleCopy}
              aria-label={copied ? "Copied" : "Copy link"}
              className="shrink-0"
            >
              {copied ? (
                <CheckIcon className="size-4 text-success" />
              ) : (
                <CopyIcon className="size-4" />
              )}
            </Button>
          </div>
          {copied && (
            <p className="text-xs text-success">Link copied to clipboard!</p>
          )}
        </Field>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Close
          </Button>
          {onEmailLink && (
            <Button onClick={onEmailLink} disabled={isSendingEmail}>
              {isSendingEmail ? (
                <>
                  <Spinner className="size-3.5" />
                  Sending…
                </>
              ) : (
                "Email link"
              )}
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ---------------------------------------------------------------------------
// EmailTemplateDialog
// ---------------------------------------------------------------------------

export interface EmailTemplateDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  contactName: string;
  contactEmail: string;
  defaultSubject?: string;
  defaultBody?: string;
  onSend: (payload: { subject: string; body: string }) => void;
  isSending?: boolean;
  className?: string;
}

export function EmailTemplateDialog({
  open,
  onOpenChange,
  contactName,
  contactEmail,
  defaultSubject = "",
  defaultBody = "",
  onSend,
  isSending = false,
  className,
}: EmailTemplateDialogProps) {
  const [subject, setSubject] = React.useState(defaultSubject);
  const [body, setBody] = React.useState(defaultBody);

  React.useEffect(() => {
    if (open) {
      setSubject(defaultSubject);
      setBody(defaultBody);
    }
  }, [open, defaultSubject, defaultBody]);

  const canSend = subject.trim() !== "" && body.trim() !== "" && !isSending;

  return (
    <Dialog open={open} onOpenChange={isSending ? undefined : onOpenChange}>
      <DialogContent size="lg" className={className}>
        <DialogHeader>
          <DialogTitle>Send Email</DialogTitle>
        </DialogHeader>

        <div className="flex flex-col gap-4">
          {/* To — read-only recipient display */}
          <Field label="To">
            <div className="flex items-center gap-2 border border-border bg-muted/40 px-3 py-2 text-sm">
              <span className="font-medium text-foreground">{contactName}</span>
              <span className="text-muted-foreground">
                &lt;{contactEmail}&gt;
              </span>
            </div>
          </Field>

          <Field id="etd-subject" label="Subject" required>
            <Input
              id="etd-subject"
              placeholder="Email subject"
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              disabled={isSending}
            />
          </Field>

          <Field id="etd-body" label="Message" required>
            <Textarea
              id="etd-body"
              rows={8}
              placeholder="Write your message here…"
              value={body}
              onChange={(e) => setBody(e.target.value)}
              disabled={isSending}
            />
          </Field>
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isSending}
          >
            Cancel
          </Button>
          <Button onClick={() => onSend({ subject, body })} disabled={!canSend}>
            {isSending ? (
              <>
                <Spinner className="size-3.5" />
                Sending…
              </>
            ) : (
              "Send Email"
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ---------------------------------------------------------------------------
// ShareContactDialog
// ---------------------------------------------------------------------------

export interface InternalAdvisor {
  id: string;
  name: string;
  role: string;
  practice: string;
}

export interface ShareContactDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  contactName: string;
  internalAdvisors: InternalAdvisor[];
  onShareInternal: (advisorId: string, notes: string) => void;
  onShareExternal: (payload: {
    firstName: string;
    lastName: string;
    email: string;
    notes: string;
  }) => void;
  isSending?: boolean;
  className?: string;
}

export function ShareContactDialog({
  open,
  onOpenChange,
  contactName,
  internalAdvisors,
  onShareInternal,
  onShareExternal,
  isSending = false,
  className,
}: ShareContactDialogProps) {
  const [tab, setTab] = React.useState("internal");
  const [search, setSearch] = React.useState("");
  const [selectedId, setSelectedId] = React.useState<string | null>(null);
  const [internalNotes, setInternalNotes] = React.useState("");
  const [firstName, setFirstName] = React.useState("");
  const [lastName, setLastName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [externalNotes, setExternalNotes] = React.useState("");

  function reset() {
    setTab("internal");
    setSearch("");
    setSelectedId(null);
    setInternalNotes("");
    setFirstName("");
    setLastName("");
    setEmail("");
    setExternalNotes("");
  }

  function handleOpenChange(v: boolean) {
    if (!v) reset();
    onOpenChange(v);
  }

  const filtered = internalAdvisors.filter((a) => {
    const q = search.toLowerCase();
    return a.name.toLowerCase().includes(q) || a.role.toLowerCase().includes(q);
  });

  return (
    <Dialog open={open} onOpenChange={isSending ? undefined : handleOpenChange}>
      <DialogContent size="md" className={className}>
        <DialogHeader>
          <DialogTitle>Share Client's Information</DialogTitle>
        </DialogHeader>

        <p className="text-sm text-muted-foreground">
          Share{" "}
          <span className="font-medium text-foreground">{contactName}</span>
          's information with an advisor.
        </p>

        <Tabs value={tab} onValueChange={setTab}>
          <TabsList className="w-full">
            <TabsTrigger value="internal" className="flex-1">
              Internal Advisor
            </TabsTrigger>
            <TabsTrigger value="external" className="flex-1">
              External / Referral
            </TabsTrigger>
          </TabsList>

          <TabsContent value="internal" className="mt-4 flex flex-col gap-4">
            <Field label="Search Advisor">
              <Input
                placeholder="Search by name or role…"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
              />
            </Field>

            <div className="max-h-[200px] overflow-y-auto border border-border divide-y divide-border">
              {filtered.length === 0 ? (
                <p className="px-3 py-4 text-center text-sm text-muted-foreground">
                  No advisors found.
                </p>
              ) : (
                filtered.map((a) => {
                  const isSelected = selectedId === a.id;
                  return (
                    <button
                      key={a.id}
                      type="button"
                      onClick={() => setSelectedId(a.id)}
                      className={cn(
                        "flex w-full items-center gap-3 px-3 py-2.5 text-left transition-colors hover:bg-muted/40",
                        isSelected && "bg-primary/5",
                      )}
                    >
                      <div
                        className={cn(
                          "flex size-4 shrink-0 items-center justify-center rounded-full border-2",
                          isSelected
                            ? "border-primary"
                            : "border-border bg-background",
                        )}
                      >
                        {isSelected && (
                          <div className="size-2 rounded-full bg-primary" />
                        )}
                      </div>
                      <div>
                        <p className="text-sm font-medium">{a.name}</p>
                        <p className="text-xs text-muted-foreground">
                          {a.role} · {a.practice}
                        </p>
                      </div>
                    </button>
                  );
                })
              )}
            </div>

            <Field id="sc-int-notes" label="Notes">
              <Textarea
                id="sc-int-notes"
                placeholder="Optional message for the advisor…"
                rows={3}
                value={internalNotes}
                onChange={(e) => setInternalNotes(e.target.value)}
                disabled={isSending}
              />
            </Field>
          </TabsContent>

          <TabsContent value="external" className="mt-4 flex flex-col gap-4">
            <div className="grid grid-cols-2 gap-4">
              <Field id="sc-first" label="First Name">
                <Input
                  id="sc-first"
                  placeholder="First name"
                  value={firstName}
                  onChange={(e) => setFirstName(e.target.value)}
                  disabled={isSending}
                />
              </Field>
              <Field id="sc-last" label="Last Name">
                <Input
                  id="sc-last"
                  placeholder="Last name"
                  value={lastName}
                  onChange={(e) => setLastName(e.target.value)}
                  disabled={isSending}
                />
              </Field>
            </div>

            <Field id="sc-email" label="Email" required>
              <Input
                id="sc-email"
                type="email"
                placeholder="advisor@company.com.au"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                disabled={isSending}
              />
            </Field>

            <Field id="sc-ext-notes" label="Notes">
              <Textarea
                id="sc-ext-notes"
                placeholder="Optional message…"
                rows={3}
                value={externalNotes}
                onChange={(e) => setExternalNotes(e.target.value)}
                disabled={isSending}
              />
            </Field>
          </TabsContent>
        </Tabs>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => handleOpenChange(false)}
            disabled={isSending}
          >
            Cancel
          </Button>
          {tab === "internal" ? (
            <Button
              onClick={() => onShareInternal(selectedId!, internalNotes)}
              disabled={!selectedId || isSending}
            >
              {isSending ? (
                <>
                  <Spinner className="size-3.5" />
                  Sharing…
                </>
              ) : (
                "Share Client"
              )}
            </Button>
          ) : (
            <Button
              onClick={() =>
                onShareExternal({
                  firstName,
                  lastName,
                  email,
                  notes: externalNotes,
                })
              }
              disabled={!email || isSending}
            >
              {isSending ? (
                <>
                  <Spinner className="size-3.5" />
                  Sending…
                </>
              ) : (
                "Send Invite"
              )}
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
