import type { CustomerInput as AccountInput } from './customers';
import { apiRequest, getApiBaseUrl } from './api';
import type { BadgeTone } from '../components/platform/platformTypes';
import { UserRole } from '../context/AuthContext';

export type LeadStatus = 'NEW' | 'CONTACTED' | 'QUALIFIED' | 'NURTURING' | 'UNQUALIFIED' | 'CONVERTED';

export type LeadView = 'all' | 'mine' | 'new' | 'converted';
export type LeadSort = 'name' | 'status' | 'serviceInterest' | 'source' | 'owner' | 'estimatedValue' | 'createdAt' | 'nextFollowUpAt';

export interface Lead {
  id: string;
  name: string;
  company: string;
  title: string | null;
  email: string;
  phone: string | null;
  city: string | null;
  source: string | null;
  serviceInterest: string | null;
  status: LeadStatus;
  estimatedValue: number;
  convertedAccountId: string | null;
  convertedContactId: string | null;
  convertedDealId: string | null;
  convertedAt: string | null;
  nextFollowUpAt: string | null;
  convertedAccount: { id: string; name: string; customerNumber: string | null } | null;
  convertedContact: { id: string; name: string } | null;
  convertedDeal: {
    id: string;
    dealNumber: string;
    title: string;
    stage: string;
    amount: number;
  } | null;
  owner: { id: string; name: string } | null;
  createdAt: string;
  updatedAt: string;
}

export type LeadCounts = Record<LeadView, number>;

export interface LeadPage {
  items: Lead[];
  total: number;
  page: number;
  pageSize: number;
  counts: LeadCounts;
}

export interface CrmNote {
  id: string;
  body: string;
  author: { id: string; name: string } | null;
  createdAt: string;
}

export type LeadNote = CrmNote;

export interface DirectoryUser {
  id: string;
  name: string;
  role: UserRole;
}

export interface LeadInput {
  name: string;
  company: string;
  email?: string;
  phone?: string | null;
  title?: string | null;
  city?: string | null;
  source?: string | null;
  serviceInterest?: string | null;
  status?: LeadStatus;
  estimatedValue?: number;
  ownerId?: string | null;
  nextFollowUpAt?: string | null;
}

export type FollowUpFilter = 'all' | 'overdue' | 'today' | 'this_week' | 'upcoming';

export interface LeadQuery {
  view: LeadView;
  q?: string;
  status?: LeadStatus;
  source?: string;
  serviceInterest?: string;
  ownerId?: string;
  followUp?: FollowUpFilter;
  createdFrom?: string;
  createdTo?: string;
  sort?: LeadSort;
  dir?: 'asc' | 'desc';
  page?: number;
  pageSize?: number;
}

export const STATUS_LABEL: Record<LeadStatus, string> = {
  NEW: 'New Enquiry',
  CONTACTED: 'Follow-up In Progress',
  NURTURING: 'Discussion / Demo Scheduled',
  QUALIFIED: 'Requirement Approved',
  UNQUALIFIED: 'Not Interested / Dropped',
  CONVERTED: 'Converted to Customer',
};

export const STATUS_TONE: Record<LeadStatus, BadgeTone> = {
  NEW: 'blue',
  CONTACTED: 'indigo',
  QUALIFIED: 'green',
  NURTURING: 'amber',
  UNQUALIFIED: 'gray',
  CONVERTED: 'accent',
};

export const LEAD_VIEWS: Array<{ key: LeadView; label: string }> = [
  { key: 'all', label: 'All Leads' },
  { key: 'mine', label: 'My Leads' },
  { key: 'converted', label: 'Converted Leads' },
];

export function inr(value: number): string {
  if (!value) return '₹0';
  return new Intl.NumberFormat('en-IN', {
    style: 'currency',
    currency: 'INR',
    maximumFractionDigits: 0,
  }).format(value);
}

export function inrFull(value: number): string {
  return new Intl.NumberFormat('en-IN', {
    style: 'currency',
    currency: 'INR',
    maximumFractionDigits: 0,
  }).format(value);
}

export const LEADS_CHANGED_EVENT = 'tcx:leads-changed';
export function notifyLeadsChanged() {
  if (typeof window !== 'undefined') {
    window.dispatchEvent(new Event(LEADS_CHANGED_EVENT));
  }
}

function toQueryString(q: LeadQuery): string {
  const params = new URLSearchParams();
  Object.entries(q).forEach(([k, v]) => {
    if (v !== undefined && v !== null && v !== '') params.set(k, String(v));
  });
  return params.toString();
}

export interface ConvertLeadInput {
  customer?: AccountInput;
  accountId?: string;
  newAccount?: boolean;
  lifecycle?: 'Customer' | 'Prospect' | 'Partner';
  createDeal?: boolean;
  dealTitle?: string;
  dealAmount?: number;
  engagementModel?: string | null;
  estimatedHours?: number | null;
}

export interface ConvertLeadResult {
  lead: Lead;
  account: { id: string; name: string; customerNumber: string | null };
  contact: { id: string; name: string; email: string; accountId: string };
  deal: {
    id: string;
    dealNumber: string;
    title: string;
    stage: string;
    amount: number;
  } | null;
  reusedAccount: boolean;
}

export const leadsApi = {
  list: (q: LeadQuery) => apiRequest<LeadPage>(`/leads?${toQueryString(q)}`),
  summary: () => apiRequest<LeadCounts>('/leads/summary'),
  get: (id: string) => apiRequest<Lead>(`/leads/${encodeURIComponent(id)}`),
  create: (input: LeadInput) => apiRequest<Lead>('/leads', { method: 'POST', body: JSON.stringify(input) }),
  update: (id: string, input: Partial<LeadInput>) =>
    apiRequest<Lead>(`/leads/${encodeURIComponent(id)}`, {
      method: 'PATCH',
      body: JSON.stringify(input),
    }),
  remove: (id: string) =>
    apiRequest<{ id: string }>(`/leads/${encodeURIComponent(id)}`, {
      method: 'DELETE',
    }),
  convert: (id: string, input: ConvertLeadInput = {}) =>
    apiRequest<ConvertLeadResult>(`/leads/${encodeURIComponent(id)}/convert`, {
      method: 'POST',
      body: JSON.stringify(input),
    }),
  notes: (id: string) => apiRequest<LeadNote[]>(`/leads/${encodeURIComponent(id)}/notes`),
  addNote: (id: string, body: string) =>
    apiRequest<LeadNote>(`/leads/${encodeURIComponent(id)}/notes`, {
      method: 'POST',
      body: JSON.stringify({ body }),
    }),
  directory: () => apiRequest<DirectoryUser[]>('/organization/directory'),
  downloadPdf: async (id: string): Promise<void> => {
    const token = typeof window !== 'undefined' ? localStorage.getItem('tcx_access_token') : null;
    const baseUrl = getApiBaseUrl();
    const res = await fetch(`${baseUrl}/leads/${encodeURIComponent(id)}/pdf`, {
      headers: token ? { Authorization: `Bearer ${token}` } : {},
      credentials: 'include',
    });
    if (!res.ok) {
      const err = await res.json().catch(() => ({ message: 'Download failed' }));
      throw new Error(err.message || 'Failed to download lead PDF');
    }
    const blob = await res.blob();
    const disposition = res.headers.get('content-disposition') || '';
    const match = disposition.match(/filename="?([^";]+)"?/);
    const filename = match ? match[1] : `lead-${id}.pdf`;

    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(url);
  },
};

export function canDeleteRecords(user?: { role: string; canDelete?: boolean; customRole?: { permissions?: Array<{ module: string; canDelete: boolean }> } | null } | null, module?: string): boolean {
  if (!user) return false;
  if (user.role === UserRole.ORGANIZATION_ADMIN || user.role === UserRole.PLATFORM_ADMIN) return true;
  if (user.customRole?.permissions && user.customRole.permissions.length > 0 && module) {
    const modPerm = user.customRole.permissions.find((p) => p.module === module);
    if (modPerm) return Boolean(modPerm.canDelete);
  }
  return Boolean(user.canDelete);
}
