import React from "react";
import {
  ArrowLeft,
  Briefcase,
  Calendar,
  CheckCircle2,
  ChevronRight,
  Circle,
  HelpCircle,
  Link2,
  Mail,
  MapPin,
  Navigation,
  Phone,
  PhoneCall,
  Plus,
  Sparkles,
  UserPlus,
  Video,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import type {
  AiConvAppointmentData,
  AiConvContact,
  AiConvDataField,
  AiConvMeetingType,
} from "./types";
import {
  ContactAvatar,
  displayContactName,
  PANEL_HEADER_HEIGHT,
} from "./helpers";

// ---------------------------------------------------------------------------
// AICollectedDataSection
// ---------------------------------------------------------------------------

export interface AICollectedDataSectionProps {
  fields: AiConvDataField[];
  className?: string;
}

export function AICollectedDataSection({
  fields,
  className,
}: AICollectedDataSectionProps) {
  return (
    <div className={cn("flex flex-col", className)}>
      {fields.map((field, i) => (
        <div
          key={i}
          className="flex items-center justify-between gap-2 border-b border-border/40 py-1.5 last:border-b-0"
        >
          <span className="shrink-0 text-sm text-muted-foreground">
            {field.label}
          </span>
          <div className="flex items-center gap-1.5">
            <span className="text-right text-sm font-medium text-foreground">
              {field.value}
            </span>
            {field.confidence === "confirmed" ? (
              <CheckCircle2 className="size-3 shrink-0 text-success-text" />
            ) : (
              <HelpCircle className="size-3 shrink-0 text-warning-text" />
            )}
          </div>
        </div>
      ))}
    </div>
  );
}

// ---------------------------------------------------------------------------
// LeadInfoPanel — internal helpers
// ---------------------------------------------------------------------------

const APPOINTMENT_STATUS_LABEL: Record<
  AiConvAppointmentData["status"],
  string
> = {
  requested: "Lead requested",
  confirmed: "Confirmed",
  pending: "Pending confirmation",
  cancelled: "Cancelled",
};

const MEETING_ICON: Record<AiConvMeetingType, React.ElementType> = {
  video: Video,
  phone: Phone,
  "in-person": MapPin,
};

const MEETING_LABEL: Record<AiConvMeetingType, string> = {
  video: "Video Call",
  phone: "Phone Call",
  "in-person": "In Person",
};

const MEETING_DETAIL_ICON: Record<AiConvMeetingType, React.ElementType> = {
  video: Link2,
  phone: PhoneCall,
  "in-person": Navigation,
};

function MeetingDetailRow({
  meetingType,
  detail,
}: {
  meetingType: AiConvMeetingType;
  detail: string;
}) {
  const DetailIcon = MEETING_DETAIL_ICON[meetingType];
  const isLink = detail.startsWith("http");
  return (
    <div className="flex items-center gap-2">
      <DetailIcon className="size-4 shrink-0 text-muted-foreground" />
      {isLink ? (
        <a
          href={detail}
          target="_blank"
          rel="noopener noreferrer"
          className="text-sm text-primary underline underline-offset-2 break-all hover:text-primary/80"
        >
          {detail}
        </a>
      ) : (
        <span className="text-sm text-muted-foreground break-all">
          {detail}
        </span>
      )}
    </div>
  );
}

interface AppointmentSectionProps {
  appointment: AiConvAppointmentData;
  contactId: string;
  isAnonymous: boolean;
  onApproveAppointment?: () => void;
  onDeclineAppointment?: () => void;
  onRescheduleAppointment?: (contactId: string) => void;
}

function AppointmentSection({
  appointment,
  contactId,
  isAnonymous,
  onApproveAppointment,
  onDeclineAppointment,
  onRescheduleAppointment,
}: AppointmentSectionProps) {
  const AppointmentIcon = MEETING_ICON[appointment.meetingType];
  const canReschedule = !isAnonymous && !!onRescheduleAppointment;

  return (
    <div className="flex flex-col gap-2">
      <div className="flex items-center gap-2">
        <Calendar className="size-3.5 shrink-0 text-muted-foreground" />
        <span className="text-sm font-medium text-foreground">
          {appointment.datetime}
        </span>
      </div>
      <div className="flex items-center gap-2">
        <AppointmentIcon className="size-4 shrink-0 text-muted-foreground" />
        <span className="text-sm text-muted-foreground">
          {MEETING_LABEL[appointment.meetingType]}
        </span>
      </div>
      {appointment.meetingDetail && (
        <MeetingDetailRow
          meetingType={appointment.meetingType}
          detail={appointment.meetingDetail}
        />
      )}
      <span
        className={cn("text-sm font-medium", {
          "text-warning-text": appointment.status === "requested",
          "text-success-text": appointment.status === "confirmed",
          "text-muted-foreground": appointment.status === "pending",
          "text-destructive line-through": appointment.status === "cancelled",
        })}
      >
        {APPOINTMENT_STATUS_LABEL[appointment.status]}
      </span>

      {appointment.status === "requested" && (
        <div className="flex gap-2 pt-1">
          <Button size="sm" className="flex-1" onClick={onApproveAppointment}>
            Approve
          </Button>
          <Button
            variant="outline"
            size="sm"
            className="flex-1"
            onClick={onDeclineAppointment}
          >
            Decline
          </Button>
          {canReschedule && (
            <Button
              variant="ghost"
              size="sm"
              className="flex-1"
              onClick={() => onRescheduleAppointment!(contactId)}
            >
              Reschedule
            </Button>
          )}
        </div>
      )}

      {(appointment.status === "confirmed" ||
        appointment.status === "cancelled") &&
        canReschedule && (
          <Button
            variant="outline"
            size="sm"
            className="mt-1 w-full justify-start"
            onClick={() => onRescheduleAppointment!(contactId)}
          >
            Reschedule
          </Button>
        )}

      {(appointment.summary || (appointment.actionItems?.length ?? 0) > 0) && (
        <div className="mt-1 flex flex-col gap-2 border-t border-border pt-3">
          <div className="flex items-center gap-2">
            <Sparkles className="size-3.5 shrink-0 text-muted-foreground" />
            <span className="text-sm font-medium text-foreground">
              Meeting Summary
            </span>
          </div>
          {appointment.summary && (
            <p className="text-sm text-muted-foreground">
              {appointment.summary}
            </p>
          )}
          {(appointment.actionItems?.length ?? 0) > 0 && (
            <div className="flex flex-col gap-1.5">
              {appointment.actionItems?.map((item, i) => (
                <div key={i} className="flex items-start gap-2 text-sm">
                  {item.done ? (
                    <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
                  ) : (
                    <Circle className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
                  )}
                  <span
                    className={cn("text-foreground", {
                      "text-muted-foreground line-through": item.done,
                    })}
                  >
                    {item.label}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function PanelSectionHeader({ children }: { children: React.ReactNode }) {
  return (
    <p className="mb-2.5 text-overline text-muted-foreground">{children}</p>
  );
}

function PanelSection({
  children,
  last = false,
}: {
  children: React.ReactNode;
  last?: boolean;
}) {
  return (
    <div className={cn("px-4 py-4", !last && "border-b border-border")}>
      {children}
    </div>
  );
}

// ---------------------------------------------------------------------------
// LeadInfoPanel
// ---------------------------------------------------------------------------

export interface LeadInfoPanelProps {
  contact: AiConvContact;
  firstSeen?: string;
  source?: string;
  /** Conversation topic tag — e.g. "Buy a Home", "Refinance", "Investment". */
  topic?: string;
  aiFields?: AiConvDataField[];
  appointment?: AiConvAppointmentData;
  internalNotes?: string;
  notesSaveStatus?: "idle" | "saving" | "saved";
  isCollapsed?: boolean;
  /** True when this lead's contact info already exists in the system. Disables Add to Clients. */
  isKnownContact?: boolean;
  onAddToContacts?: () => void;
  onCreateOpportunity?: () => void;
  onBookAppointment?: () => void;
  onApproveAppointment?: () => void;
  onDeclineAppointment?: () => void;
  onRescheduleAppointment?: (contactId: string) => void;
  onNotesChange?: (v: string) => void;
  onToggleCollapse?: () => void;
  /** Mobile only — back to chat thread. */
  onBack?: () => void;
  className?: string;
}

export function LeadInfoPanel({
  contact,
  firstSeen,
  source = "Website Chatbot",
  topic,
  aiFields = [],
  appointment,
  internalNotes = "",
  notesSaveStatus = "idle",
  isCollapsed = false,
  isKnownContact = false,
  onAddToContacts,
  onCreateOpportunity,
  onBookAppointment,
  onApproveAppointment,
  onDeclineAppointment,
  onRescheduleAppointment,
  onNotesChange,
  onToggleCollapse,
  onBack,
  className,
}: LeadInfoPanelProps) {
  const isAnonymous = !contact.name.trim();
  const addToContactsDisabled = isAnonymous || isKnownContact;

  return (
    <div className={cn("flex flex-col bg-background", className)}>
      <div
        className={cn(
          PANEL_HEADER_HEIGHT,
          "flex items-center justify-between border-b border-border px-4",
        )}
      >
        {onBack && (
          <Button
            variant="ghost"
            size="icon"
            className="size-8 shrink-0 md:hidden"
            onClick={onBack}
            aria-label="Back to conversation"
          >
            <ArrowLeft className="size-4" />
          </Button>
        )}
        <span className="text-sm font-semibold text-foreground">Lead Info</span>
        {onToggleCollapse && (
          <Tooltip>
            <TooltipTrigger
              render={
                <Button
                  variant="ghost"
                  size="icon"
                  className="size-7"
                  onClick={onToggleCollapse}
                  aria-label={isCollapsed ? "Expand panel" : "Collapse panel"}
                >
                  <ChevronRight
                    className={cn(
                      "size-4 transition-transform duration-150",
                      isCollapsed && "-rotate-180",
                    )}
                  />
                </Button>
              }
            />
            <TooltipContent>
              {isCollapsed ? "Expand panel" : "Collapse panel"}
            </TooltipContent>
          </Tooltip>
        )}
      </div>

      {!isCollapsed && (
        <div className="flex-1 overflow-y-auto" tabIndex={0}>
          <PanelSection>
            <PanelSectionHeader>Client</PanelSectionHeader>
            <div className="flex items-center gap-3">
              <ContactAvatar name={contact.name} size="lg" />
              <div className="min-w-0 flex-1">
                <p className="truncate text-sm font-semibold text-foreground">
                  {displayContactName(contact.name)}
                </p>
                <p className="text-sm text-muted-foreground">{source}</p>
                {topic && (
                  <Badge variant="secondary" className="mt-1 text-xs">
                    {topic}
                  </Badge>
                )}
              </div>
            </div>
            {(contact.email || contact.phone || firstSeen) && (
              <div className="mt-3 flex flex-col gap-1.5">
                {contact.email && (
                  <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <Mail className="size-4 shrink-0" />
                    <a
                      href={`mailto:${contact.email}`}
                      className="truncate hover:underline"
                    >
                      {contact.email}
                    </a>
                  </div>
                )}
                {contact.phone && (
                  <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <PhoneCall className="size-4 shrink-0" />
                    <a
                      href={`tel:${contact.phone}`}
                      className="hover:underline"
                    >
                      {contact.phone}
                    </a>
                  </div>
                )}
                {firstSeen && (
                  <p className="text-sm text-muted-foreground">
                    First seen: {firstSeen}
                  </p>
                )}
              </div>
            )}
          </PanelSection>

          <PanelSection>
            <PanelSectionHeader>AI-Collected Data</PanelSectionHeader>
            {aiFields.length > 0 ? (
              <>
                <AICollectedDataSection fields={aiFields} />
                <div className="mt-2.5 flex items-center gap-3 text-xs text-muted-foreground">
                  <span className="flex items-center gap-1">
                    <CheckCircle2 className="size-3 text-success-text" />
                    confirmed
                  </span>
                  <span className="flex items-center gap-1">
                    <HelpCircle className="size-3 text-warning-text" />
                    estimated
                  </span>
                </div>
              </>
            ) : (
              <p className="text-sm text-muted-foreground">
                AI is still gathering information...
              </p>
            )}
          </PanelSection>

          <PanelSection>
            <PanelSectionHeader>Appointment</PanelSectionHeader>
            {appointment ? (
              <AppointmentSection
                appointment={appointment}
                contactId={contact.id}
                isAnonymous={isAnonymous}
                onApproveAppointment={onApproveAppointment}
                onDeclineAppointment={onDeclineAppointment}
                onRescheduleAppointment={onRescheduleAppointment}
              />
            ) : (
              <Button
                variant="outline"
                size="sm"
                className="w-full justify-start"
                disabled={isAnonymous}
                onClick={onBookAppointment}
              >
                <Plus className="mr-1.5 size-3.5" />
                Book Appointment
              </Button>
            )}
          </PanelSection>

          <PanelSection>
            <PanelSectionHeader>CRM Actions</PanelSectionHeader>
            <div className="flex flex-col gap-2">
              <Tooltip>
                <TooltipTrigger
                  render={
                    <Button
                      variant="outline"
                      size="sm"
                      className="w-full justify-start"
                      disabled={addToContactsDisabled}
                      onClick={onAddToContacts}
                    >
                      <UserPlus className="mr-1.5 size-3.5" />
                      Add to Clients
                    </Button>
                  }
                />
                {isKnownContact && (
                  <TooltipContent>Already a client</TooltipContent>
                )}
              </Tooltip>
              <Button
                variant="outline"
                size="sm"
                className="w-full justify-start"
                disabled={isAnonymous}
                onClick={onCreateOpportunity}
              >
                <Briefcase className="mr-1.5 size-3.5" />
                Add to CRM
              </Button>
            </div>
          </PanelSection>

          <PanelSection last>
            <div className="mb-2.5 flex items-center justify-between">
              <p className="text-overline text-muted-foreground">
                Internal Notes
              </p>
              {notesSaveStatus === "saving" && (
                <span className="text-xs text-muted-foreground">Saving...</span>
              )}
              {notesSaveStatus === "saved" && (
                <span className="flex items-center gap-1 text-xs text-success-text">
                  <CheckCircle2 className="size-3" />
                  Saved
                </span>
              )}
            </div>
            <Textarea
              value={internalNotes}
              onChange={(e) => onNotesChange?.(e.target.value)}
              placeholder="Private notes — not visible to lead..."
              rows={4}
              className="resize-none text-sm"
            />
          </PanelSection>
        </div>
      )}
    </div>
  );
}
