const SIZES=["YS","YM","YL","S","M","L","XL","2XL"];
const SECCIONES=["Design","Roster","Quote","Production"];

// Tile de resumen para el dashboard de Production.
function Kpi({label,value}){
  return <Card padding="18px" style={{display:"flex",flexDirection:"column",gap:6}}>
    <span style={{fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:".1em",color:"var(--text-muted)"}}>{label}</span>
    <span style={{fontSize:24,fontWeight:700,letterSpacing:"-.01em"}}>{value}</span>
  </Card>;
}

// Enviar el proof pide la fecha de cierre del roster: es lo que el cliente ve como "Closes …".
function EnviarProof({open,onClose,onSend,version}){
  const [fecha,setFecha]=React.useState("");
  React.useEffect(()=>{if(open)setFecha(window.ORDENES.enDias(10))},[open]);
  return <Dialog open={open} onClose={onClose} title="Send for approval" width={420}
    description="The customer gets a link to approve the design and add players until the roster closes."
    footer={<Button size="sm" disabled={!fecha.trim()} onClick={()=>onSend(fecha.trim())}>Send for approval</Button>}>
    <div style={{marginTop:8}}>
      <Input label="Roster closes on" value={fecha} onChange={e=>setFecha(e.target.value)} hint="Shown to the customer. You can close the roster earlier."/>
    </div>
  </Dialog>;
}

// El roster tiene dos origenes: lo que piden los padres desde el proof y lo que
// el Member anade o importa. El conteo por talla se calcula; nunca se teclea.
function RosterPedido({order:o,editable,onChange}){
  const O=window.ORDENES;
  const [f,setF]=React.useState({name:"",num:"",size:"M",qty:1});
  const add=()=>{if(!f.name.trim())return;onChange([...o.roster,{...f,name:f.name.trim(),by:"member"}]);setF({name:"",num:"",size:"M",qty:1})};
  const tallas=O.tallas(o.roster);
  const cols=[
    {key:"name",label:"Player"},
    {key:"num",label:"No.",width:64},
    {key:"size",label:"Size",width:64},
    {key:"qty",label:"Qty",width:56,align:"right"},
    {key:"by",label:"Added by",width:100,render:r=><span style={{color:"var(--text-muted)"}}>{r.by==="viewer"?"Parent":"You"}</span>}
  ];
  if(editable)cols.push({key:"x",label:"",width:44,align:"right",render:r=><IconButton label={"Remove "+r.name} size="sm" variant="ghost"
    onClick={()=>onChange(o.roster.filter(x=>x!==r))}><Icon name="trash-2" size={15}/></IconButton>});
  const abierto=["draft","changes","proof","open"].includes(o.status);
  return <div style={{display:"flex",flexDirection:"column",gap:14}}>
    {o.roster.length>0&&<div style={{display:"flex",gap:16,flexWrap:"wrap",alignItems:"baseline",fontSize:12,color:"var(--text-muted)"}}>
      {SIZES.filter(s=>tallas[s]).map(s=><span key={s}><b style={{color:"var(--text-body)"}}>{s}</b> {tallas[s]}</span>)}
      <span style={{marginLeft:"auto",fontSize:13,fontWeight:700,color:"var(--text-body)"}}>{O.unidades(o.roster)} pcs</span>
    </div>}
    {editable&&<UploadBox height={100} vectorize={false} title="Drop a roster here" accept="XLSX, CSV" hint="Columns: name, number, size. Each row becomes a player."/>}
    {editable&&<div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(120px,1fr))",gap:10,alignItems:"end"}}>
      <Input label="Player name" value={f.name} placeholder="Add manually" onChange={e=>setF({...f,name:e.target.value})}/>
      <Input label="Number" value={f.num} placeholder="12" onChange={e=>setF({...f,num:e.target.value})}/>
      <Select label="Size" options={SIZES} value={f.size} onChange={e=>setF({...f,size:e.target.value})}/>
      <NumberInput label="Qty" value={f.qty} min={1} onChange={v=>setF({...f,qty:v})} width="auto"/>
      <Button variant="outline" onClick={add} iconLeft={<Icon name="plus" size={16}/>}>Add</Button>
    </div>}
    {o.roster.length
      ?<div style={{overflowX:"auto"}}><Table dense columns={cols} rows={o.roster} style={{minWidth:480}}/></div>
      :<span style={{fontSize:13,color:"var(--text-muted)"}}>No players yet. Parents add themselves from the share link; you can add or import here.</span>}
    {o.closes&&<span style={{fontSize:13,color:"var(--text-muted)"}}>{abierto?"Closes ":"Closed "}{o.closes}</span>}
  </div>;
}

function Cotizacion({order:o}){
  const O=window.ORDENES,D=O.dinero;
  // En "closed" la cifra aun no esta congelada: se ensena la que saldria.
  const q=o.quote||(o.status==="closed"?O.cotizar(o):null);
  if(!q)return <span style={{fontSize:13,color:"var(--text-muted)"}}>The quote is generated when you close the roster.</span>;
  const lines=q.lineas.map(l=>({desc:l.desc,qty:l.qty,unit:D(l.unit),total:D(l.importe)}));
  const cols=[{key:"desc",label:"Line item"},{key:"qty",label:"Qty",align:"right",width:70},{key:"unit",label:"Unit",align:"right",width:90},{key:"total",label:"Total",align:"right",width:110}];
  return <div style={{display:"flex",flexDirection:"column",gap:14}}>
    {!o.quote&&<span style={{fontSize:12,color:"var(--text-muted)"}}>Draft quote from {q.unidades} players. Send it to freeze the numbers.</span>}
    <div style={{overflowX:"auto"}}><Table dense columns={cols} rows={lines} style={{minWidth:480}}/></div>
    <div style={{display:"flex",flexDirection:"column",gap:6,alignSelf:"flex-end",minWidth:220}}>
      {[["Subtotal",D(q.subtotal)],["Tax",D(q.tax)]].map(([k,v])=>
        <div key={k} style={{display:"flex",justifyContent:"space-between",fontSize:13}}><span style={{color:"var(--text-muted)"}}>{k}</span><span>{v}</span></div>)}
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"baseline",borderTop:"2px solid var(--bruce-black)",paddingTop:10,marginTop:4}}>
        <span style={{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:".06em"}}>Total</span>
        <span style={{fontSize:28,fontWeight:700,letterSpacing:"-.01em"}}>{D(q.total)}</span>
      </div>
    </div>
    {o.quote&&<div><Button variant="outline" size="sm" iconLeft={<Icon name="file-text" size={16}/>}>Download quote PDF</Button></div>}
  </div>;
}

// El expediente. Una sola vista con cuatro secciones; el stepper de la cabecera
// es el unico stepper y navega hacia los pasos ya cumplidos.
function OrderDetail({order:o,role,avanzar,actualizar,comentar,abrirEnvio,onEnvioAbierto,verCliente,go,editar}){
  const P=window.PASOS,O=window.ORDENES,p=P[o.status];
  const tope=Math.min(p.paso,SECCIONES.length-1);
  const [seccion,setSeccion]=React.useState(tope);
  React.useEffect(()=>{setSeccion(Math.min(P[o.status].paso,SECCIONES.length-1))},[o.status]);
  const [enviar,setEnviar]=React.useState(false);
  React.useEffect(()=>{if(abrirEnvio){setEnviar(true);onEnvioAbierto&&onEnvioAbierto()}},[abrirEnvio]);
  const [share,setShare]=React.useState(false);
  const [nota,setNota]=React.useState("");
  const rosterEditable=p.paso<3;
  const tallas=O.tallas(o.roster);
  const set=k=>e=>actualizar(o.id,{[k]:e.target.value});
  const ejecutar=()=>{if(["draft","changes"].includes(o.status))setEnviar(true);else avanzar(o.id,p.a)};
  const mandar=fecha=>{actualizar(o.id,{closes:fecha});avanzar(o.id,"proof");setEnviar(false)};
  const postear=()=>{if(!nota.trim())return;comentar(o.id,nota.trim());setNota("")};
  const link="https://bruce.app/p/"+o.id;

  // El diseno y el producto viven lado a lado: Design a la izquierda, Product
  // (garment/fabric/decoration + notas, de donde sale la cotizacion) a la derecha,
  // alineados arriba. Envuelven en flex-wrap para apilarse en pantallas estrechas.
  const cuerpo=[
    <div key="d" style={{display:"flex",gap:20,alignItems:"flex-start",flexWrap:"wrap"}}>
      <div style={{flex:"1.4 1 320px",minWidth:0,display:"flex",flexDirection:"column",gap:20}}>
        <Bloque title="Design" action={<>
            <Button size="sm" variant="ghost" onClick={()=>setShare(true)} iconLeft={<Icon name="share-2" size={14}/>}>Share</Button>
            <Button size="sm" variant="outline" onClick={()=>verCliente(o.id)}>Preview as customer</Button></>}>
          {/* Editar el diseno es un icono dentro del propio lienzo, arriba a la derecha. */}
          <div style={{position:"relative"}}>
            <Lienzo label={o.design} src={arteDe(o.design)} aspect="1 / 1"/>
            <IconButton label="Edit design" size="sm" onClick={()=>editar(o.id)}
              style={{position:"absolute",top:10,right:10,background:"var(--bruce-white)",
                border:"var(--border-width-hairline) solid var(--border-hairline)",boxShadow:"var(--shadow-sm)"}}>
              <Icon name="square-pen" size={16}/>
            </IconButton>
          </div>
          {o.proofs.length===0&&<span style={{fontSize:13,color:"var(--text-muted)"}}>Not sent yet. The customer sees this once you send it for approval.</span>}
        </Bloque>
        {/* Los comentarios viven con el diseno: bajo su tarjeta y en su misma columna. */}
        <Bloque>
          <Textarea label="Add a comment" rows={3} value={nota} onChange={e=>setNota(e.target.value)} placeholder="Anything the team should know."/>
          <div><Button size="sm" variant="outline" disabled={!nota.trim()} onClick={postear}>Post comment</Button></div>
          <div>{o.log.map((e,i)=><Entrada key={i} {...e}/>)}</div>
        </Bloque>
      </div>
      <div style={{flex:"1 1 280px",minWidth:0}}>
        <Bloque title="Product">
          <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(160px,1fr))",gap:16}}>
            <Select label="Garment" options={Object.keys(window.DATA.precios.garment)} value={o.garment} onChange={set("garment")} disabled={!rosterEditable}/>
            <Select label="Fabric" options={window.DATA.fabrics} value={o.fabric} onChange={set("fabric")} disabled={!rosterEditable}/>
            <Select label="Decoration" options={window.DATA.decorations} value={o.decoration} onChange={set("decoration")} disabled={!rosterEditable}/>
          </div>
          <Textarea label="Production notes" rows={3} value={o.notes} onChange={set("notes")} placeholder="Anything the decorator should know." disabled={!rosterEditable}/>
          {!rosterEditable&&<span style={{fontSize:12,color:"var(--text-subtle)"}}>Locked with the roster: the quote is built from these.</span>}
        </Bloque>
      </div>
    </div>,
    <Bloque key="r" title="Roster">
      <RosterPedido order={o} editable={rosterEditable} onChange={r=>actualizar(o.id,{roster:r})}/>
    </Bloque>,
    <Bloque key="q" title="Quote"><Cotizacion order={o}/></Bloque>,
    // Production: dashboard. Resume lo esencial de cada paso, sin tablas ni detalle.
    <div key="p" style={{display:"flex",flexDirection:"column",gap:20}}>
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(150px,1fr))",gap:16}}>
        <Kpi label="Ship by" value={o.due||"—"}/>
        <Kpi label="Pieces" value={O.unidades(o.roster)+" pcs"}/>
        <Kpi label="Quote total" value={o.quote?O.dinero(o.quote.total):"—"}/>
        <Kpi label="Status" value={p.label}/>
      </div>
      <div style={{display:"flex",gap:20,flexWrap:"wrap",alignItems:"flex-start"}}>
        <div style={{flex:"1.5 1 300px",minWidth:0}}>
          <Bloque title="Design">
            <Lienzo label={o.design} src={arteDe(o.design)} height={200}/>
            <div style={{display:"flex",flexDirection:"column",gap:8}}>
              {[["Garment",o.garment],["Fabric",o.fabric],["Decoration",o.decoration]].map(([k,v])=>
                <div key={k} style={{display:"flex",justifyContent:"space-between",gap:12,fontSize:13}}>
                  <span style={{color:"var(--text-muted)"}}>{k}</span><span style={{fontWeight:600,textAlign:"right"}}>{v}</span></div>)}
            </div>
          </Bloque>
        </div>
        <div style={{flex:"1 1 240px",minWidth:0,display:"flex",flexDirection:"column",gap:20}}>
          <Bloque title="Roster">
            <div style={{display:"flex",gap:10,flexWrap:"wrap",fontSize:13,color:"var(--text-muted)"}}>
              {SIZES.filter(s=>tallas[s]).map(s=><span key={s}><b style={{color:"var(--text-body)"}}>{s}</b> {tallas[s]}</span>)}
            </div>
            <div style={{fontSize:24,fontWeight:700,letterSpacing:"-.01em"}}>{O.unidades(o.roster)} <span style={{fontSize:13,fontWeight:400,color:"var(--text-muted)"}}>pcs · {o.roster.length} players</span></div>
          </Bloque>
          <Bloque title="Quote">
            {o.quote
              ?<div style={{display:"flex",flexDirection:"column",gap:6}}>
                {[["Subtotal",O.dinero(o.quote.subtotal)],["Tax",O.dinero(o.quote.tax)]].map(([k,v])=>
                  <div key={k} style={{display:"flex",justifyContent:"space-between",fontSize:13}}><span style={{color:"var(--text-muted)"}}>{k}</span><span>{v}</span></div>)}
                <div style={{display:"flex",justifyContent:"space-between",alignItems:"baseline",borderTop:"2px solid var(--bruce-black)",paddingTop:8,marginTop:2}}>
                  <span style={{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:".06em"}}>Total</span>
                  <span style={{fontSize:22,fontWeight:700}}>{O.dinero(o.quote.total)}</span></div>
              </div>
              :<span style={{fontSize:13,color:"var(--text-muted)"}}>Not quoted yet.</span>}
          </Bloque>
        </div>
      </div>
      <Bloque title="Production notes">
        <Textarea rows={3} value={o.prodNotes||""} onChange={set("prodNotes")}
          placeholder="Anything the production team should know — packing, deadlines, special handling."/>
      </Bloque>
    </div>
  ][seccion];

  return <div style={{display:"flex",flexDirection:"column",gap:20}}>
    <ShareDialog open={share} onClose={()=>setShare(false)} link={link} subject={"Design for "+o.team}
      note="Anyone with the link can approve the design and add players. They do not need an account."
      onShared={c=>comentar(o.id,"Shared the design via "+c,"event")}/>
    <EnviarProof open={enviar} onClose={()=>setEnviar(false)} onSend={mandar} version={o.proofs.length+1}/>
    <Stepper steps={window.STEPS} current={p.paso} onSelect={i=>{if(i<=tope)setSeccion(i)}}/>
    {/* El contexto (solo cuando aplica): esperar al cliente o pedido cerrado. */}
    <Espera order={o} role={role}/>
    {!p.actua&&<div style={{display:"flex",alignItems:"center",gap:8,fontSize:13,color:"var(--text-muted)"}}>
      <Icon name="circle-check" size={16} strokeColor="var(--bruce-black)"/><span>Shipped on {o.due}. Nothing left to do.</span></div>}
    {/* La accion de avance vive en la misma fila que las pestañas, justificada al lado opuesto. */}
    <div style={{display:"flex",alignItems:"flex-end",justifyContent:"space-between",gap:16,flexWrap:"wrap",
      borderBottom:"var(--border-width-hairline) solid var(--border-hairline)"}}>
      <Tabs tabs={SECCIONES.slice(0,tope+1)} value={SECCIONES[seccion]} onChange={t=>setSeccion(SECCIONES.indexOf(t))} style={{borderBottom:"none"}}/>
      <div style={{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",paddingBottom:6}}>
        {o.status==="proof"
          ?<>
            <Button size="sm" onClick={()=>avanzar(o.id,"open",null,"Approved the design")}>Approve & open roster</Button>
            <Button size="sm" variant="ghost" onClick={()=>avanzar(o.id,"changes",null,"Requested changes")}>Log change request</Button>
          </>
          :p.accion&&<Button size="sm" onClick={ejecutar}>{p.accion}</Button>}
      </div>
    </div>
    {cuerpo}
  </div>;
}
window.OrderDetail=OrderDetail;
