import { useState } from "react";
import { Handshake, Users } from "lucide-react";
import { trpc } from "@/lib/trpc";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { EntitySidebar } from "@/components/EntitySidebar";
import { EntitySearchSelect, type EntityOption } from "@/components/EntitySearchSelect";
import { ContactDetailSheet, type CreatedContact } from "@/components/ContactDetailSheet";
import { PHASE_CONFIG, PHASE_OPTIONS, type PhaseOption } from "@/lib/phase-config";

interface MainContact {
  id?: number;
  firstName?: string;
  lastName?: string;
  mail?: string;
}

interface Deal {
  id?: number;
  name?: string;
  phase?: string;
  mainContact?: MainContact[];
  createdAt?: string;
  updatedAt?: string;
}

interface DealDetailSheetProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  dealId?: number | null;
  onSuccess?: () => void;
  layer?: number;
}

// Component for rendering phase option with icon
function PhaseOptionDisplay({ phase }: { phase: PhaseOption }) {
  const config = PHASE_CONFIG[phase];
  if (!config) return <span>{phase}</span>;
  
  const Icon = config.icon;
  
  return (
    <div className="flex items-center gap-2">
      <div className={`p-1 rounded ${config.bgColor}`}>
        <Icon className={`h-3.5 w-3.5 ${config.color}`} />
      </div>
      <span>{config.label}</span>
    </div>
  );
}

// Helper to format contact name
function formatContactName(contact: MainContact): string {
  const parts = [contact.firstName, contact.lastName].filter(Boolean);
  return parts.join(" ") || "Unknown";
}

export function DealDetailSheet({
  open,
  onOpenChange,
  dealId,
  onSuccess,
  layer = 0,
}: DealDetailSheetProps) {
  const isCreateMode = !dealId;

  // Contact search state
  const [contactSearchQuery, setContactSearchQuery] = useState("");
  const [contactSheetOpen, setContactSheetOpen] = useState(false);

  const { data: dealData, isLoading } = trpc.deals.getById.useQuery(
    { id: dealId! },
    { enabled: !!dealId && open }
  );

  // Search contacts
  const { data: contactSearchResults, isLoading: isSearchingContacts } = trpc.contacts.search.useQuery(
    { query: contactSearchQuery, limit: 5 },
    { enabled: open }
  );
  
  // Cast to Deal type to work around complex type inference
  const deal = dealData as Deal | null | undefined;

  // Get initial contact from deal data
  const getInitialContact = (): EntityOption | null => {
    if (isCreateMode || !deal?.mainContact?.[0]) return null;
    const contact = deal.mainContact[0];
    if (!contact.id) return null;
    return {
      id: contact.id,
      name: formatContactName(contact),
      subtitle: contact.mail,
    };
  };

  // Use deal data as initial values, track changes separately
  const initialName = isCreateMode ? "" : (deal?.name || "");
  const initialPhase: PhaseOption = isCreateMode ? "New" : ((deal?.phase as PhaseOption) || "New");
  const initialContact = getInitialContact();

  const [name, setName] = useState("");
  const [phase, setPhase] = useState<PhaseOption>("New");
  const [selectedContact, setSelectedContact] = useState<EntityOption | null>(null);
  const [isInitialized, setIsInitialized] = useState(false);

  // Initialize form when data loads or sheet opens
  if (open && !isLoading && !isInitialized) {
    setName(initialName);
    setPhase(initialPhase);
    setSelectedContact(initialContact);
    setIsInitialized(true);
  }

  // Reset when sheet closes
  if (!open && isInitialized) {
    setIsInitialized(false);
  }

  // Check if contact changed
  const contactChanged = isCreateMode
    ? selectedContact !== null
    : (selectedContact?.id !== initialContact?.id);

  const hasChanges = isCreateMode 
    ? name.trim().length > 0 
    : (name !== initialName || phase !== initialPhase || contactChanged);

  const createMutation = trpc.deals.create.useMutation({
    onSuccess: () => {
      onSuccess?.();
      onOpenChange(false);
    },
  });

  const updateMutation = trpc.deals.update.useMutation({
    onSuccess: () => {
      onSuccess?.();
      onOpenChange(false);
    },
  });

  const deleteMutation = trpc.deals.delete.useMutation({
    onSuccess: () => {
      onSuccess?.();
      onOpenChange(false);
    },
  });

  const handleSave = () => {
    if (isCreateMode) {
      if (name.trim()) {
        createMutation.mutate({
          name,
          phase: phase as "New" | "Demo scheduled" | "Contract signed" | "Lost",
          mainContact: selectedContact ? [selectedContact.id] : undefined,
        });
      }
    } else if (dealId && hasChanges) {
      updateMutation.mutate({
        id: dealId,
        name: name || undefined,
        phase: phase as "New" | "Demo scheduled" | "Contract signed" | "Lost",
        mainContact: selectedContact ? [selectedContact.id] : [],
      });
    }
  };

  const handleDelete = () => {
    if (dealId) {
      deleteMutation.mutate({ id: dealId });
    }
  };

  // Handle contact creation success
  const handleContactCreated = () => {
    // Refetch contacts after creation
    setContactSearchQuery("");
  };

  const isPending = createMutation.isPending || updateMutation.isPending;

  // Map contact search results to EntityOption format
  const contactOptions: EntityOption[] = (contactSearchResults || [])
    .filter((c): c is { id: number; firstName: string; lastName: string; mail?: string } => 
      c.id !== undefined && c.firstName !== undefined && c.lastName !== undefined
    )
    .map((contact) => ({
      id: contact.id,
      name: `${contact.firstName} ${contact.lastName}`,
      subtitle: contact.mail,
    }));

  return (
    <>
      <EntitySidebar
        open={open}
        onOpenChange={onOpenChange}
        title={isCreateMode ? "New Deal" : "Deal Details"}
        description={isCreateMode ? "Create a new deal record" : "View and edit deal information"}
        icon={<Handshake className="h-5 w-5 text-primary" />}
        isCreateMode={isCreateMode}
        isLoading={isLoading}
        hasChanges={hasChanges}
        isPending={isPending}
        isDeletePending={deleteMutation.isPending}
        onSave={handleSave}
        onDelete={isCreateMode ? undefined : handleDelete}
        layer={layer}
        footer={
          !isCreateMode && deal ? (
            <div className="pt-4 border-t">
              <p className="text-xs text-muted-foreground">
                Created: {deal.createdAt ? new Date(deal.createdAt).toLocaleDateString() : "-"}
                {deal.updatedAt && (
                  <> | Updated: {new Date(deal.updatedAt).toLocaleDateString()}</>
                )}
              </p>
            </div>
          ) : undefined
        }
      >
        <div className="space-y-2">
          <Label htmlFor="name">Deal Name *</Label>
          <Input
            id="name"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Enterprise Contract Q1"
          />
        </div>

        <div className="space-y-2">
          <Label htmlFor="phase">Phase *</Label>
          <Select value={phase} onValueChange={(value) => setPhase(value as PhaseOption)}>
            <SelectTrigger id="phase">
              <SelectValue>
                <PhaseOptionDisplay phase={phase} />
              </SelectValue>
            </SelectTrigger>
            <SelectContent>
              {PHASE_OPTIONS.map((option) => (
                <SelectItem key={option} value={option}>
                  <PhaseOptionDisplay phase={option} />
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="space-y-2">
          <Label>Main Contact</Label>
          <EntitySearchSelect
            value={selectedContact}
            onChange={setSelectedContact}
            onSearch={setContactSearchQuery}
            onCreateNew={() => setContactSheetOpen(true)}
            options={contactOptions}
            isLoading={isSearchingContacts}
            placeholder="Select a contact..."
            icon={Users}
            entityName="Contact"
          />
        </div>

      </EntitySidebar>

      {/* Nested Contact Creation Sheet */}
      <ContactDetailSheet
        open={contactSheetOpen}
        onOpenChange={setContactSheetOpen}
        contactId={null}
        layer={layer + 1}
        onSuccess={(newContact?: CreatedContact) => {
          handleContactCreated();
          if (newContact) {
            setSelectedContact({
              id: newContact.id,
              name: `${newContact.firstName} ${newContact.lastName}`,
              subtitle: newContact.mail,
            });
          }
          setContactSheetOpen(false);
        }}
      />
    </>
  );
}
