"use client";

import { FormEvent, useEffect, useMemo, useState } from "react";

type Company={id:string;name:string;shortName:string};
type Flow={companyId:string;kind:"client"|"fournisseur";party:string;isForecast?:boolean};
type Policy={id:number;companyId:string;supplierName:string;supplierKey:string;priorityRank:number;splittable:boolean;maxInstallmentMonths:number;paymentDeadline?:string|null};

const normalized=(value:unknown)=>String(value??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").trim().toLowerCase();

export function SupplierPoliciesPage(){
  const [companies,setCompanies]=useState<Company[]>([]); const [flows,setFlows]=useState<Flow[]>([]); const [policies,setPolicies]=useState<Policy[]>([]); const [busy,setBusy]=useState(false); const [notice,setNotice]=useState(""); const [query,setQuery]=useState("");
  const embedded=typeof window!=="undefined"&&new URLSearchParams(window.location.search).get("embedded")==="1";
  const refresh=async()=>{const [treasuryResponse,settingsResponse]=await Promise.all([fetch("/api/treasury"),fetch("/api/treasury/settings")]);if(treasuryResponse.ok){const data=await treasuryResponse.json();setCompanies(Array.isArray(data.companies)?data.companies:[]);setFlows(Array.isArray(data.flows)?data.flows:[]);}if(settingsResponse.ok){const data=await settingsResponse.json();setPolicies(Array.isArray(data.supplierPolicies)?data.supplierPolicies:[]);}};
  useEffect(()=>{let cancelled=false;void Promise.all([fetch("/api/treasury"),fetch("/api/treasury/settings")]).then(async([treasuryResponse,settingsResponse])=>{const [treasuryData,settingsData]=await Promise.all([treasuryResponse.ok?treasuryResponse.json():null,settingsResponse.ok?settingsResponse.json():null]);if(cancelled)return;if(treasuryData){setCompanies(Array.isArray(treasuryData.companies)?treasuryData.companies:[]);setFlows(Array.isArray(treasuryData.flows)?treasuryData.flows:[]);}if(settingsData)setPolicies(Array.isArray(settingsData.supplierPolicies)?settingsData.supplierPolicies:[]);});return()=>{cancelled=true}},[]);
  const candidates=useMemo(()=>Array.from(new Map(flows.filter(flow=>flow.kind==="fournisseur"&&!flow.isForecast).map(flow=>[`${flow.companyId}::${normalized(flow.party)}`,{companyId:flow.companyId,supplierName:flow.party}])).values()).filter(item=>!query||normalized(item.supplierName).includes(normalized(query))).sort((a,b)=>{const aPolicy=policies.find(policy=>policy.companyId===a.companyId&&policy.supplierKey===normalized(a.supplierName));const bPolicy=policies.find(policy=>policy.companyId===b.companyId&&policy.supplierKey===normalized(b.supplierName));if(aPolicy&&bPolicy)return aPolicy.priorityRank-bPolicy.priorityRank;if(aPolicy)return -1;if(bPolicy)return 1;return a.supplierName.localeCompare(b.supplierName,"fr")}),[flows,policies,query]);
  const policyFor=(companyId:string,supplierName:string)=>policies.find(policy=>policy.companyId===companyId&&policy.supplierKey===normalized(supplierName));
  const companyName=(id:string)=>companies.find(company=>company.id===id)?.shortName||id.toUpperCase();
  const back=()=>window.location.assign(`/treasury/plan-intelligent${embedded?"?embedded=1":""}`);
  async function save(event:FormEvent<HTMLFormElement>,companyId:string,supplierName:string){event.preventDefault();const data=new FormData(event.currentTarget),splittable=data.get("splittable")==="true",priorityRank=Number(data.get("priorityRank")),maxInstallmentMonths=splittable?Number(data.get("maxInstallmentMonths")):1,paymentDeadline=String(data.get("paymentDeadline")||"");if(!window.confirm(`Enregistrer la politique de ${supplierName} ?\n\nPriorité ${priorityRank} · ${splittable?`${maxInstallmentMonths} mensualité(s)`:"paiement intégral"}${paymentDeadline?` · limite ${new Date(`${paymentDeadline}T00:00:00`).toLocaleDateString("fr-FR")}`:""}`))return;setBusy(true);setNotice("");try{const response=await fetch("/api/treasury/settings",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({resource:"supplierPaymentPolicy",companyId,supplierName,priorityRank,splittable,maxInstallmentMonths,paymentDeadline})}),result=await response.json().catch(()=>({}));if(!response.ok)throw new Error(result.error||"Enregistrement impossible");await refresh();setNotice(`Politique de ${supplierName} enregistrée.`);}catch(error){setNotice(error instanceof Error?error.message:"Enregistrement impossible");}finally{setBusy(false)}}
  async function remove(policy:Policy){if(!window.confirm(`Repasser ${policy.supplierName} en simulation libre ?`))return;setBusy(true);setNotice("");try{const response=await fetch("/api/treasury/settings",{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({resource:"supplierPaymentPolicy",id:policy.id})}),result=await response.json().catch(()=>({}));if(!response.ok)throw new Error(result.error||"Suppression impossible");await refresh();setNotice(`${policy.supplierName} est désormais simulé librement.`);}catch(error){setNotice(error instanceof Error?error.message:"Suppression impossible");}finally{setBusy(false)}}
  return <main className="supplier-policies-page"><header className="supplier-policies-page-head"><div><span>PLAN INTELLIGENT · POLITIQUES FOURNISSEURS</span><h1>Politiques de règlement par fournisseur</h1><p>Définissez l’ordre de priorité, le nombre de mensualités et la date limite. Les fournisseurs sans politique restent en simulation libre.</p></div><button type="button" onClick={back}>← Revenir au plan intelligent</button></header><section className="supplier-policies-toolbar"><label><span>Rechercher un fournisseur</span><input type="search" value={query} onChange={event=>setQuery(event.target.value)} placeholder="Nom du fournisseur…"/></label><div><span>Politiques actives</span><b>{policies.length}</b></div><div><span>Simulation libre</span><b>{Math.max(0,candidates.length-policies.length)}</b></div></section>{notice&&<p className="supplier-policy-notice" role="status">{notice}</p>}<section className="supplier-policy-page-table"><div className="head"><span>Fournisseur</span><span>Priorité</span><span>Fractionnable</span><span>Nombre de mois</span><span>Date limite</span><span>Action</span></div>{candidates.map((candidate,index)=>{const policy=policyFor(candidate.companyId,candidate.supplierName);return <form className={policy?"configured":"free"} key={`${candidate.companyId}-${candidate.supplierName}`} onSubmit={event=>void save(event,candidate.companyId,candidate.supplierName)}><span><b>{candidate.supplierName}</b><small>{companyName(candidate.companyId)} · {policy?"politique active":"simulation libre"}</small></span><label><small>Rang</small><input name="priorityRank" type="number" min="1" max="999" defaultValue={policy?.priorityRank||index+1} required/></label><label><small>Mode</small><select name="splittable" defaultValue={String(policy?.splittable??true)}><option value="true">Oui</option><option value="false">Non · intégral</option></select></label><label><small>Mensualités</small><input name="maxInstallmentMonths" type="number" min="1" max="24" defaultValue={policy?.maxInstallmentMonths||3} required/></label><label><small>Au plus tard</small><input name="paymentDeadline" type="date" defaultValue={policy?.paymentDeadline||""}/></label><span className="actions"><button disabled={busy}>{policy?"Mettre à jour":"Enregistrer"}</button>{policy&&<button type="button" className="free" disabled={busy} onClick={()=>void remove(policy)}>Simulation libre</button>}</span></form>})}</section><footer><span>Règle de sécurité</span>Une politique contrainte qui ne peut pas être financée dans le délai reste à arbitrer et n’est jamais appliquée automatiquement.</footer></main>;
}
