File size: 79,804 Bytes
266eda8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
"""
Lab ECM Batch Creation Form
- Document ECM processing (decell, wash, lyoph, reconstitute, etc.)
- Characterize batch (protein, pH, conductivity, UV, etc.)
- Output: batch_id for use in gelation experiments
- No plates, no wells (batch exists independently)
"""

import streamlit as st
import sqlite3
import pandas as pd
from datetime import datetime, date
from pathlib import Path
import json
import os

# Import shared utilities
# Define fallback constants first
COMMON_DILUENTS = ["PBS", "Water", "Tris", "HEPES", "Acetic acid", "Other"]
COMMON_BUFFERS = [
    "PBS",
    "Tris-HCl",
    "HEPES", 
    "MOPS",
    "MES",
    "Sodium phosphate",
    "Potassium phosphate",
    "Other"
]
COMMON_ENZYMES = [
    "Trypsin",
    "Collagenase",
    "Dispase", 
    "Accutase",
    "Proteinase K",
    "Papain",
    "Elastase",
    "Other"
]
DECELL_AGENTS = [
    "SDS (Sodium dodecyl sulfate)",
    "Triton X-100", 
    "Tween-20",
    "Sodium deoxycholate",
    "CHAPS",
    "N-lauroylsarcosine sodium salt",
    "Peracetic acid",
    "Acetic acid",
    "Freeze-thaw (physical)",
    "Hypotonic/hypertonic",
    "Trypsin",
    "Collagenase", 
    "Dispase",
    "Accutase",
    "Other"
]
DELIPID_SOLVENTS = [
    "Isopropanol",
    "Ethanol", 
    "Acetone",
    "Chloroform/methanol",
    "Petroleum ether",
    "Chloroform",
    "Methanol",
    "Other"
]
COMMON_BASES = ["NaOH", "KOH", "NH4OH", "Other"]
COMMON_ACIDS = ["HCl", "H2SO4", "HNO3", "Other"]
COMMON_SALTS = ["NaCl", "KCl", "CaCl2", "MgCl2", "Other"]
REAGENT_PURPOSES = ["neutralization", "ionic_adjust", "pH_adjust", "other"]

# Try to import from shared_parameters and override fallbacks
try:
    from shared_parameters import *
except ImportError:
    # Fallback for cloud deployment
    import sys
    import os
    sys.path.append(os.path.dirname(os.path.abspath(__file__)))
    try:
        from shared_parameters import *
    except ImportError:
        # Keep the fallback constants defined above
        pass

# ============================================================================
# DATABASE CONNECTION
# ============================================================================

ROOT = Path(__file__).resolve().parents[1]
DB_PATH = Path(os.getenv("GELPREDICT_DB", str(ROOT / "gelpredict.db"))).resolve()

def get_connection():
    con = sqlite3.connect(str(DB_PATH))
    con.row_factory = sqlite3.Row
    con.execute("PRAGMA foreign_keys=ON;")
    con.execute("PRAGMA journal_mode=WAL;")
    return con

def _connect():
    """Consistent connection function following app pattern"""
    return get_connection()

def tx():
    """Context manager for transactions"""
    from contextlib import contextmanager
    @contextmanager
    def _tx():
        con = get_connection()
        try:
            con.execute("BEGIN IMMEDIATE;")
            yield con
            con.execute("COMMIT;")
        except Exception as e:
            con.execute("ROLLBACK;")
            raise e
        finally:
            con.close()
    return _tx()

# ============================================================================
# BATCH ID GENERATION
# ============================================================================

def generate_batch_id(family: str, species: str = None, tissue: str = None, 
                      date_obj=None, is_commercial: bool = False) -> str:
    """
    Auto-generate batch_id from ECM metadata.
    Format: {family_abbrev}-{species_abbrev}{tissue_abbrev}-{YYMMDD}
    """
    if is_commercial:
        return ""  # Commercial uses lot number
    
    parts = []
    
    # Family abbreviation
    family_map = {
        "decECM": "dECM",
        "collagen": "COL",
        "fibrin": "FIB",
        "alginate": "ALG",
        "gelMA": "gMA",
        "gelatin": "GEL",
        "hyaluronan": "HA",
        "PEG_DA": "PEG",
        "composite": "COMP",
        "other": "OTH"
    }
    parts.append(family_map.get(family, family[:4].upper()))
    
    # Species-tissue for decECM
    if family == "decECM" and species and tissue:
        species_map = {"human": "Hu", "porcine": "Por", "bovine": "Bov", 
                      "rat": "Rat", "mouse": "Mou", "avian": "Avi"}
        tissue_map = {"mammary": "Mam", "dermis": "Der", "small_intestine_submucosa": "SIS",
                     "myocardium": "Myo", "liver": "Liv", "lung": "Lun"}
        sp = species_map.get(species, species[:3].title())
        ts = tissue_map.get(tissue, tissue[:3].title())
        parts.append(f"{sp}{ts}")
    
    # Date
    if date_obj:
        if isinstance(date_obj, str):
            dt = datetime.fromisoformat(date_obj)
        else:
            dt = date_obj
        parts.append(dt.strftime("%y%m%d"))
    else:
        parts.append(datetime.now().strftime("%y%m%d"))
    
    return "-".join(parts)

# ============================================================================
# UI
# ============================================================================

def _show_edit_batch_form(batch_id, conn):
    """Show form to edit an existing batch."""
    st.header(f"✏️ Edit Batch: {batch_id}")
    
    # Get current batch data
    batch_data = pd.read_sql_query("""
        SELECT * FROM ecm_batches_lab WHERE batch_id = ?
    """, conn, params=(batch_id,)).iloc[0]
    
    st.info("⚠️ **Edit Mode**: Modifying an existing batch. Changes will be saved immediately.")
    
    # Pre-populate form with existing data
    col1, col2 = st.columns(2)
    
    with col1:
        new_batch_id = st.text_input("Batch ID", value=batch_data['batch_id'], key=f"edit_batch_id_{batch_id}")
        operator_id = st.text_input("Operator ID", value=batch_data['operator_id'], key=f"edit_operator_{batch_id}")
        family = st.selectbox("ECM Family", ["collagen", "decECM", "fibrin", "alginate", "gelMA", "gelatin", "hyaluronan", "PEG_DA", "composite", "other"], 
                             index=["collagen", "decECM", "fibrin", "alginate", "gelMA", "gelatin", "hyaluronan", "PEG_DA", "composite", "other"].index(batch_data['family']),
                             key=f"edit_family_{batch_id}")
    
    with col2:
        species = st.text_input("Species", value=batch_data['species'] or "", key=f"edit_species_{batch_id}")
        tissue = st.text_input("Tissue", value=batch_data['tissue'] or "", key=f"edit_tissue_{batch_id}")
        source_description = st.text_area("Source Description", value=batch_data['source_description'] or "", key=f"edit_source_{batch_id}")
    
    # Processing steps and characterization (read-only for now)
    if batch_data['processing_steps']:
        st.subheader("🧪 Processing Steps")
        processing_steps = json.loads(batch_data['processing_steps'])
        if processing_steps:
            for i, step in enumerate(processing_steps, 1):
                with st.expander(f"Step {i}: {step.get('type', 'Unknown').title()}", expanded=False):
                    for key, value in step.items():
                        if key != 'type' and value is not None:
                            st.write(f"**{key.replace('_', ' ').title()}:** {value}")
        else:
            st.info("No processing steps recorded")
    
    if batch_data['characterization']:
        st.subheader("🔬 Characterization Data")
        characterization = json.loads(batch_data['characterization'])
        if characterization:
            char_cols = st.columns(2)
            for i, (key, value) in enumerate(characterization.items()):
                if value is not None:
                    with char_cols[i % 2]:
                        st.write(f"**{key.replace('_', ' ').title()}:** {value}")
        else:
            st.info("No characterization data recorded")
    
    # Save/Cancel buttons
    col1, col2 = st.columns(2)
    
    with col1:
        if st.button("💾 Save Changes", key=f"save_edit_{batch_id}", type="primary"):
            try:
                # Update batch record
                conn.execute("""
                    UPDATE ecm_batches_lab 
                    SET batch_id = ?, operator_id = ?, family = ?, species = ?, tissue = ?, 
                        source_description = ?, updated_at = ?
                    WHERE batch_id = ?
                """, (new_batch_id, operator_id, family, species, tissue, source_description, 
                      datetime.now().isoformat(), batch_id))
                
                conn.commit()
                st.success(f"✅ Batch **{new_batch_id}** updated successfully!")
                st.rerun()
                
            except Exception as e:
                st.error(f"❌ Error updating batch: {e}")
    
    with col2:
        if st.button("❌ Cancel", key=f"cancel_edit_{batch_id}"):
            st.rerun()

def _show_delete_batch_confirmation(batch_id, conn):
    """Show confirmation dialog for deleting a batch."""
    st.header(f"🗑️ Delete Batch: {batch_id}")
    
    # Get batch data to show what will be deleted
    batch_data = pd.read_sql_query("""
        SELECT * FROM ecm_batches_lab WHERE batch_id = ?
    """, conn, params=(batch_id,)).iloc[0]
    
    st.warning("⚠️ **This action cannot be undone!**")
    
    st.write("**Batch to be deleted:**")
    st.write(f"- **Batch ID:** {batch_data['batch_id']}")
    st.write(f"- **Family:** {batch_data['family']}")
    st.write(f"- **Species:** {batch_data['species'] or 'N/A'}")
    st.write(f"- **Tissue:** {batch_data['tissue'] or 'N/A'}")
    st.write(f"- **Operator:** {batch_data['operator_id']}")
    st.write(f"- **Created:** {batch_data['created_at']}")
    
    if batch_data['processing_steps']:
        processing_steps = json.loads(batch_data['processing_steps'])
        st.write(f"- **Processing Steps:** {len(processing_steps)} steps")
    
    col1, col2 = st.columns(2)
    
    with col1:
        if st.button("🗑️ Delete Permanently", key=f"confirm_delete_{batch_id}", type="primary"):
            try:
                # Use a fresh connection for the delete operation
                with sqlite3.connect(DB_PATH) as delete_conn:
                    cursor = delete_conn.execute("DELETE FROM ecm_batches_lab WHERE batch_id = ?", (batch_id,))
                    delete_conn.commit()
                    
                    if cursor.rowcount > 0:
                        st.success(f"✅ Batch **{batch_id}** deleted successfully!")
                        st.rerun()
                    else:
                        st.error(f"❌ Batch **{batch_id}** not found or already deleted.")
                        
            except Exception as e:
                st.error(f"❌ Error deleting batch: {e}")
                st.error(f"Details: {str(e)}")
    
    with col2:
        if st.button("❌ Cancel", key=f"cancel_delete_{batch_id}"):
            st.rerun()

def _show_duplicate_batch_form(batch_id, conn):
    """Show form to duplicate an existing batch."""
    st.header(f"📋 Duplicate Batch: {batch_id}")
    
    # Get current batch data
    batch_data = pd.read_sql_query("""
        SELECT * FROM ecm_batches_lab WHERE batch_id = ?
    """, conn, params=(batch_id,)).iloc[0]
    
    st.info("📋 **Duplicate Mode**: Creating a copy of an existing batch with a new ID.")
    
    # Form for new batch
    col1, col2 = st.columns(2)
    
    with col1:
        new_batch_id = st.text_input("New Batch ID", value=f"{batch_id}_copy", key=f"dup_batch_id_{batch_id}")
        operator_id = st.text_input("Operator ID", value=batch_data['operator_id'], key=f"dup_operator_{batch_id}")
        family = st.selectbox("ECM Family", ["collagen", "decECM", "fibrin", "alginate", "gelMA", "gelatin", "hyaluronan", "PEG_DA", "composite", "other"], 
                             index=["collagen", "decECM", "fibrin", "alginate", "gelMA", "gelatin", "hyaluronan", "PEG_DA", "composite", "other"].index(batch_data['family']),
                             key=f"dup_family_{batch_id}")
    
    with col2:
        species = st.text_input("Species", value=batch_data['species'] or "", key=f"dup_species_{batch_id}")
        tissue = st.text_input("Tissue", value=batch_data['tissue'] or "", key=f"dup_tissue_{batch_id}")
        source_description = st.text_area("Source Description", value=batch_data['source_description'] or "", key=f"dup_source_{batch_id}")
    
    # Show what will be copied
    st.subheader("📋 What will be copied:")
    
    if batch_data['processing_steps']:
        processing_steps = json.loads(batch_data['processing_steps'])
        st.write(f"**Processing Steps:** {len(processing_steps)} steps")
        for i, step in enumerate(processing_steps, 1):
            with st.expander(f"Step {i}: {step.get('type', 'Unknown').title()}", expanded=False):
                for key, value in step.items():
                    if key != 'type' and value is not None:
                        st.write(f"**{key.replace('_', ' ').title()}:** {value}")
    
    if batch_data['characterization']:
        characterization = json.loads(batch_data['characterization'])
        st.write("**Characterization Data:** Available")
        char_cols = st.columns(2)
        for i, (key, value) in enumerate(characterization.items()):
            if value is not None:
                with char_cols[i % 2]:
                    st.write(f"**{key.replace('_', ' ').title()}:** {value}")
    
    # Save/Cancel buttons
    col1, col2 = st.columns(2)
    
    with col1:
        if st.button("📋 Create Duplicate", key=f"save_duplicate_{batch_id}", type="primary"):
            try:
                # Check if batch ID already exists
                existing = conn.execute("SELECT COUNT(*) FROM ecm_batches_lab WHERE batch_id = ?", (new_batch_id,)).fetchone()[0]
                if existing > 0:
                    st.error(f"❌ Batch ID **{new_batch_id}** already exists. Please choose a different ID.")
                    return
                
                # Create new batch record with copied data
                conn.execute("""
                    INSERT INTO ecm_batches_lab 
                    (batch_id, operator_id, family, species, tissue, source_description, 
                     commercial_product, processing_steps, characterization, created_at, updated_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                """, (new_batch_id, operator_id, family, species, tissue, source_description,
                      batch_data['commercial_product'], batch_data['processing_steps'],
                      batch_data['characterization'], datetime.now().isoformat(), datetime.now().isoformat()))
                
                conn.commit()
                st.success(f"✅ Batch **{new_batch_id}** created successfully!")
                st.success(f"📋 Duplicated from: **{batch_id}**")
                st.rerun()
                
            except Exception as e:
                st.error(f"❌ Error creating duplicate: {e}")
    
    with col2:
        if st.button("❌ Cancel", key=f"cancel_duplicate_{batch_id}"):
            st.rerun()

def show_batch_library():
    """Display all created ECM batches with their processing steps and characterization data."""
    st.header("📚 ECM Batch Library")
    
    # Connect to database
    try:
        conn = sqlite3.connect(DB_PATH)
        
        # Check if table exists
        cursor = conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='ecm_batches_lab'")
        if not cursor.fetchone():
            st.info("No batches created yet. Create your first ECM batch to see it here!")
            conn.close()
            return
        
        # Get all batches
        df = pd.read_sql_query("""
            SELECT batch_id, operator_id, family, species, tissue, source_description, 
                   commercial_product, created_at, updated_at
            FROM ecm_batches_lab 
            ORDER BY created_at DESC
        """, conn)
        
        if df.empty:
            st.info("No batches created yet. Create your first ECM batch to see it here!")
            conn.close()
            return
        
        st.write(f"**Total batches created:** {len(df)}")
        
        # Filters
        with st.expander("🔍 Filter Batches", expanded=False):
            col1, col2, col3 = st.columns(3)
            with col1:
                filter_family = st.selectbox("ECM Family", ["All"] + df['family'].dropna().unique().tolist())
                filter_operator = st.text_input("Operator ID")
            with col2:
                filter_species = st.selectbox("Species", ["All"] + df['species'].dropna().unique().tolist())
                filter_tissue = st.selectbox("Tissue", ["All"] + df['tissue'].dropna().unique().tolist())
            with col3:
                filter_batch_id = st.text_input("Batch ID (partial match)")
        
        # Apply filters
        filtered_df = df.copy()
        if filter_family != "All":
            filtered_df = filtered_df[filtered_df['family'] == filter_family]
        if filter_operator:
            filtered_df = filtered_df[filtered_df['operator_id'].str.contains(filter_operator, case=False, na=False)]
        if filter_species != "All":
            filtered_df = filtered_df[filtered_df['species'] == filter_species]
        if filter_tissue != "All":
            filtered_df = filtered_df[filtered_df['tissue'] == filter_tissue]
        if filter_batch_id:
            filtered_df = filtered_df[filtered_df['batch_id'].str.contains(filter_batch_id, case=False, na=False)]
        
        if filtered_df.empty:
            st.warning("No batches match your filters.")
            conn.close()
            return
        
        # Display batch list
        st.write(f"**Showing {len(filtered_df)} batches:**")
        
        # Show batch summary table with action buttons
        display_cols = ['batch_id', 'family', 'species', 'tissue', 'operator_id', 'created_at']
        
        for idx, row in filtered_df.iterrows():
            with st.container():
                col1, col2, col3, col4, col5, col6, col7 = st.columns([3, 2, 2, 2, 2, 2, 3])
                
                with col1:
                    st.write(f"**{row['batch_id']}**")
                with col2:
                    st.write(row['family'])
                with col3:
                    st.write(row['species'] or 'N/A')
                with col4:
                    st.write(row['tissue'] or 'N/A')
                with col5:
                    st.write(row['operator_id'])
                with col6:
                    st.write(row['created_at'][:10])  # Just the date
                with col7:
                    # Action buttons
                    btn_col1, btn_col2, btn_col3 = st.columns(3)
                    
                    with btn_col1:
                        if st.button("✏️", key=f"edit_{row['batch_id']}", help="Edit batch"):
                            st.session_state[f"edit_batch_{row['batch_id']}"] = True
                            st.rerun()
                    
                    with btn_col2:
                        if st.button("🗑️", key=f"delete_{row['batch_id']}", help="Delete batch"):
                            st.session_state[f"delete_batch_{row['batch_id']}"] = True
                            st.rerun()
                    
                    with btn_col3:
                        if st.button("📋", key=f"duplicate_{row['batch_id']}", help="Duplicate batch"):
                            st.session_state[f"duplicate_batch_{row['batch_id']}"] = True
                            st.rerun()
                
                st.divider()
        
        # Handle edit action
        for batch_id in filtered_df['batch_id']:
            if st.session_state.get(f"edit_batch_{batch_id}"):
                st.session_state[f"edit_batch_{batch_id}"] = False
                _show_edit_batch_form(batch_id, conn)
                return
        
        # Handle delete action
        for batch_id in filtered_df['batch_id']:
            if st.session_state.get(f"delete_batch_{batch_id}"):
                st.session_state[f"delete_batch_{batch_id}"] = False
                _show_delete_batch_confirmation(batch_id, conn)
                return
        
        # Handle duplicate action
        for batch_id in filtered_df['batch_id']:
            if st.session_state.get(f"duplicate_batch_{batch_id}"):
                st.session_state[f"duplicate_batch_{batch_id}"] = False
                _show_duplicate_batch_form(batch_id, conn)
                return
        
        # Batch detail viewer
        st.subheader("📋 Batch Details")
        selected_batch = st.selectbox(
            "Select batch to view details:",
            options=[""] + filtered_df['batch_id'].tolist(),
            format_func=lambda x: f"{x}" if x else "Choose a batch..."
        )
        
        if selected_batch:
            # Get full batch data
            batch_data = pd.read_sql_query("""
                SELECT * FROM ecm_batches_lab WHERE batch_id = ?
            """, conn, params=(selected_batch,)).iloc[0]
            
            # Display batch info
            col1, col2 = st.columns(2)
            with col1:
                st.write(f"**Batch ID:** {batch_data['batch_id']}")
                st.write(f"**ECM Family:** {batch_data['family']}")
                st.write(f"**Species:** {batch_data['species'] or 'N/A'}")
                st.write(f"**Tissue:** {batch_data['tissue'] or 'N/A'}")
            with col2:
                st.write(f"**Operator:** {batch_data['operator_id']}")
                st.write(f"**Created:** {batch_data['created_at']}")
                st.write(f"**Updated:** {batch_data['updated_at']}")
            
            if batch_data['source_description']:
                st.write(f"**Source Description:** {batch_data['source_description']}")
            if batch_data['commercial_product']:
                st.write(f"**Commercial Product:** {batch_data['commercial_product']}")
            
            # Processing Steps
            if batch_data['processing_steps']:
                st.subheader("🧪 Processing Steps")
                processing_steps = json.loads(batch_data['processing_steps'])
                if processing_steps:
                    for i, step in enumerate(processing_steps, 1):
                        with st.expander(f"Step {i}: {step.get('type', 'Unknown').title()}", expanded=False):
                            for key, value in step.items():
                                if key != 'type' and value is not None:
                                    st.write(f"**{key.replace('_', ' ').title()}:** {value}")
                else:
                    st.info("No processing steps recorded")
            
            # Characterization
            if batch_data['characterization']:
                st.subheader("🔬 Characterization Data")
                characterization = json.loads(batch_data['characterization'])
                if characterization:
                    char_cols = st.columns(2)
                    for i, (key, value) in enumerate(characterization.items()):
                        if value is not None:
                            with char_cols[i % 2]:
                                st.write(f"**{key.replace('_', ' ').title()}:** {value}")
                else:
                    st.info("No characterization data recorded")
        
        conn.close()
        
    except Exception as e:
        st.error(f"Error loading batch library: {e}")
        st.info("This feature requires the batch creation system to be properly set up.")

def show_batch_creation_form(codebook):
    """Main form for creating ECM batches."""
    
    st.header("🧬 Create ECM Batch")
    st.caption("Document ECM processing to create a reusable batch_id")
    
    st.info("💡 This form creates an **ECM batch** (the material). Use the **Gelation Experiment** form to test it on plates.")
    
    # Initialize session state for protocol builder
    if "batch_proc_steps" not in st.session_state:
        st.session_state.batch_proc_steps = []
    
    # ========== BATCH IDENTITY ==========
    st.subheader("📋 Batch Identity")
    
    m1, m2, m3 = st.columns(3)
    with m1:
        date_input = st.date_input("Date*", value=date.today())
    with m2:
        operator_id = st.text_input("Operator ID*", help="Your initials")
    with m3:
        # Commercial product checkbox (needs to come before family selection)
        is_commercial = st.checkbox(
            "🏭 Commercial Product",
            value=False,
            help="Check if this is a commercial product (e.g., Matrigel, Cultrex)"
        )
    
    # Commercial details
    if is_commercial:
        st.markdown("**🏷️ Commercial Product Details**")
        COMMERCIAL_PRODUCTS = {
            "Matrigel": {"vendor": "Corning", "family": "composite"},
            "Matrigel GFR": {"vendor": "Corning", "family": "composite"},
            "Cultrex": {"vendor": "R&D Systems", "family": "collagen"},
            "Cultrex BME": {"vendor": "R&D Systems", "family": "composite"},
            "Geltrex": {"vendor": "Thermo Fisher", "family": "composite"},
            "PureCol": {"vendor": "Advanced BioMatrix", "family": "collagen"},
            "VitroCol": {"vendor": "Advanced BioMatrix", "family": "collagen"},
            "Rat Tail Collagen I": {"vendor": "Corning", "family": "collagen"},
            "Bovine Collagen I": {"vendor": "Sigma-Aldrich", "family": "collagen"},
            "Porcine Collagen I": {"vendor": "Sigma-Aldrich", "family": "collagen"},
            "Collagen I (Human)": {"vendor": "Corning", "family": "collagen"},
            "Type I Collagen": {"vendor": "Various", "family": "collagen"},
            "Gelatin (Porcine)": {"vendor": "Sigma-Aldrich", "family": "gelatin"},
            "Gelatin (Bovine)": {"vendor": "Sigma-Aldrich", "family": "gelatin"},
            "Gelatin (Fish)": {"vendor": "Sigma-Aldrich", "family": "gelatin"},
            "Custom/Other": {"vendor": "", "family": ""}
        }
        
        c1, c2 = st.columns(2)
        with c1:
            product_name = st.selectbox("Product Name*", [""] + list(COMMERCIAL_PRODUCTS.keys()))
            if product_name and product_name != "Custom/Other":
                vendor = COMMERCIAL_PRODUCTS[product_name]["vendor"]
                family_hint = COMMERCIAL_PRODUCTS[product_name]["family"]
            else:
                vendor = st.text_input("Vendor Name*")
                family_hint = None
        with c2:
            catalog_num = st.text_input("Catalog Number")
            lot_num = st.text_input("Lot Number", help="Optional - used as Batch ID if provided")
        
        website = st.text_input("Company Website", placeholder="https://www.corning.com", help="Company website URL")
        
        if product_name == "Custom/Other":
            custom_product = st.text_input("Custom Product Name*")
        else:
            custom_product = None
    else:
        product_name = vendor = catalog_num = lot_num = custom_product = website = family_hint = None
    
    # ECM Family selection (after commercial checkbox, so we can auto-fill)
    if is_commercial and family_hint:
        # Auto-fill from product
        family_idx = codebook['family'].index(family_hint) + 1 if family_hint in codebook['family'] else 0
        family = st.selectbox(
            "ECM Family (auto-filled from product)",
            options=[""] + codebook['family'],
            index=family_idx,
            help="Auto-detected from product. Can override if needed."
        )
    elif is_commercial:
        # Commercial but no hint (Custom/Other)
        family = st.selectbox(
            "ECM Family (optional for commercial)",
            options=[""] + codebook['family'],
            help="Optional - select if known"
        )
    else:
        # Lab-made (required)
        family = st.selectbox(
            "ECM Family*", 
            options=[""] + codebook['family'],
            index=2 if "decECM" in codebook['family'] else 0
        )
    
    # ECM Provenance
    st.markdown("**🧬 ECM Provenance**")
    if is_commercial:
        st.caption("⚠️ For commercial: Species/tissue often not disclosed by vendor (optional)")
    
    prov1, prov2 = st.columns(2)
    with prov1:
        # Label changes based on whether it's required
        if family == "decECM" and not is_commercial:
            label_species = "Origin Species*"
        else:
            label_species = "Origin Species (optional)" if is_commercial else "Origin Species"
        
        dec_species = st.selectbox(
            label_species,
            [""] + codebook['species'],
            index=1 if "human" in codebook['species'] else 0
        )
    with prov2:
        # Label changes based on whether it's required
        if family == "decECM" and not is_commercial:
            label_tissue = "Source Tissue*"
        else:
            label_tissue = "Source Tissue (optional)" if is_commercial else "Source Tissue"
        
        dec_tissue = st.selectbox(
            label_tissue,
            [""] + codebook['tissues'],
            index=1 if "mammary" in codebook['tissues'] else 0
        )
    
    collagen_type = st.text_input("Collagen Type (if collagen family)", 
                                  placeholder="Type I, Type II, etc.")
    
    # Generate Batch ID
    st.markdown("**🏷️ Batch ID**")
    if is_commercial and lot_num:
        batch_id = f"{product_name or 'Commercial'}-{lot_num}"
        st.success(f"✅ Batch ID: **{batch_id}**")
    elif family and not is_commercial:
        batch_id = generate_batch_id(family, dec_species, dec_tissue, date_input)
        st.success(f"✅ Auto-generated Batch ID: **{batch_id}**")
    else:
        batch_id = ""
        st.warning("⚠️ Fill in Family (and Species/Tissue for decECM) to generate Batch ID")
    
    st.markdown("---")
    
    # ========== PRE-STORAGE ==========
    st.subheader("🧊 Pre-Processing Tissue Storage")
    st.caption("⚠️ BEFORE any decellularization began (raw tissue storage)")
    
    with st.expander("Pre-Storage Details", expanded=False):
        # Fresh storage
        c1a, c1b = st.columns(2)
        with c1a:
            unk_days_4c = st.checkbox("Unknown", key="batch_unk_pre_days_4c")
            pre_storage_days_4C = st.number_input("Days at 4°C", min_value=0, value=0, 
                                                  disabled=unk_days_4c)
            if unk_days_4c:
                pre_storage_days_4C = None
        with c1b:
            pre_storage_fresh_notes = st.text_input("Fresh storage notes", 
                                                    placeholder="e.g., in PBS")
        
        # Frozen storage
        st.markdown("**Frozen Storage:**")
        c2, c3, c4 = st.columns(3)
        with c2:
            unk_frozen_mo = st.checkbox("Unknown", key="batch_unk_frozen_mo")
            pre_storage_duration_months = st.number_input("Frozen (months)", 0.0, 120.0, 0.0, 0.5,
                                                          disabled=unk_frozen_mo)
            if unk_frozen_mo:
                pre_storage_duration_months = None
        with c3:
            unk_freezer_temp = st.checkbox("Unknown", key="batch_unk_frz_temp")
            pre_storage_temp_freezer = st.number_input("Freezer temp (°C)", -200.0, 0.0, -80.0, 10.0,
                                                       disabled=unk_freezer_temp)
            if unk_freezer_temp:
                pre_storage_temp_freezer = None
        with c4:
            pre_storage_frozen_in = st.text_input("Frozen in", 
                                                  placeholder="dry, buffer, cryoprotectant")
        
        # Freeze-thaw cycles
        st.markdown("**Freeze-Thaw During Storage:**")
        ft1, ft2, ft3, ft4 = st.columns(4)
        with ft1:
            unk_ft_cyc = st.checkbox("Unknown", key="batch_unk_ft_cyc")
            pre_storage_freeze_cycles = st.number_input("# Cycles", min_value=0, value=0,
                                                        disabled=unk_ft_cyc)
            if unk_ft_cyc:
                pre_storage_freeze_cycles = None
        with ft2:
            pre_storage_thaw_method = st.selectbox("Thaw method",
                ["","passive_room_temp","37C_water_bath","4C_fridge",
                 "buffer_wash_series","PBS_series","gradual_temp_ramp","other"])
        with ft3:
            unk_thaw_dur = st.checkbox("Unk", key="batch_unk_thaw_dur")
            pre_storage_thaw_duration_min = st.number_input("Thaw duration (min)", 0.0, 1000.0, 30.0, 5.0,
                                                            disabled=unk_thaw_dur)
            if unk_thaw_dur:
                pre_storage_thaw_duration_min = None
        with ft4:
            pre_storage_ft_notes = st.text_input("FT notes",
                                                 placeholder="e.g., 3× PBS washes")
    
    st.markdown("---")
    
    # ========== ECM PROCESSING PROTOCOL ==========
    if not is_commercial:
        st.subheader("🔬 ECM Processing Protocol")
        st.caption("Build your ECM preparation protocol step-by-step")
        
        # Protocol builder buttons
        st.caption("**Add Processing Steps:**")
        row1 = st.columns(6)
        step_types = [
            ("Decell", "decell"),
            ("Wash", "wash"),
            ("Delipid", "delipid"),
            ("Enzyme", "enzyme"),
            ("Homogenize", "homogenize"),
            ("Grind", "grind")
        ]
        for i, (label, stype) in enumerate(step_types):
            with row1[i]:
                if st.button(f"➕ {label}", key=f"add_{stype}_batch"):
                    st.session_state.batch_proc_steps.append({
                        "type": stype, 
                        "id": len(st.session_state.batch_proc_steps)
                    })
                    st.rerun()
        
        row2 = st.columns(6)
        step_types2 = [
            ("Freeze-Thaw", "freeze_thaw"),
            ("Lyophilize", "lyophilize"),
            ("Reconstitute", "reconstitute"),
            ("pH Adjust", "ph_adjust"),
            ("Dialysis", "dialysis"),
            ("Filtration", "filtration")
        ]
        for i, (label, stype) in enumerate(step_types2):
            with row2[i]:
                if st.button(f"➕ {label}", key=f"add_{stype}_batch"):
                    st.session_state.batch_proc_steps.append({
                        "type": stype,
                        "id": len(st.session_state.batch_proc_steps)
                    })
                    st.rerun()
        
        row3 = st.columns(6)
        with row3[0]:
            if st.button("➕ Centrifuge", key="add_centrifuge_batch"):
                st.session_state.batch_proc_steps.append({
                    "type": "centrifuge",
                    "id": len(st.session_state.batch_proc_steps)
                })
                st.rerun()
        with row3[1]:
            if st.button("➕ Storage", key="add_storage_batch"):
                st.session_state.batch_proc_steps.append({
                    "type": "storage",
                    "id": len(st.session_state.batch_proc_steps)
                })
                st.rerun()
        with row3[2]:
            if st.button("➕ Other", key="add_other_batch"):
                st.session_state.batch_proc_steps.append({
                    "type": "other",
                    "id": len(st.session_state.batch_proc_steps)
                })
                st.rerun()
        with row3[5]:
            if st.button("🗑️ Clear All", key="clear_batch_steps"):
                st.session_state.batch_proc_steps = []
                st.rerun()
        
        if st.session_state.batch_proc_steps:
            st.caption(f"**{len(st.session_state.batch_proc_steps)} step(s) added**")
        
        # Display steps (simplified - full implementation would include all step types)
        processing_steps = []
        for i, step in enumerate(st.session_state.batch_proc_steps):
            with st.expander(f"Step {i+1}: {step['type'].title()}", expanded=True):
                if step["type"] == "reconstitute":
                    st.caption("💡 Critical: Enter lyoph weight + recon volume to calculate stock concentration")
                    
                    recol1, recol2, recol3, recol4 = st.columns(4)
                    with recol1:
                        solvent_sel = st.selectbox("Solvent", COMMON_DILUENTS, 
                                                  key=f"recon_solv_{step['id']}")
                        if solvent_sel == "Other":
                            solvent = st.text_input("Specify", key=f"recon_solv_other_{step['id']}")
                        elif solvent_sel == "Acetic acid":
                            solvent = "Acetic acid"
                            conc_val = st.number_input("Conc (% v/v)", 0.0, 100.0, 0.1, 0.01, key=f"recon_aa_conc_{step['id']}")
                            solvent = f"{conc_val}% Acetic acid"
                        else:
                            solvent = solvent_sel
                    with recol2:
                        unk_wt = st.checkbox("Unk", key=f"unk_recon_wt_{step['id']}")
                        lyoph_wt = st.number_input("Lyoph weight (mg)", 0.0, 10000.0, 100.0, 1.0,
                                                   disabled=unk_wt, key=f"recon_wt_{step['id']}")
                        if unk_wt:
                            lyoph_wt = None
                    with recol3:
                        unk_vol = st.checkbox("Unk", key=f"unk_recon_vol_{step['id']}")
                        recon_vol = st.number_input("Recon volume (mL)", 0.0, 1000.0, 10.0, 0.1,
                                                    disabled=unk_vol, key=f"recon_vol_{step['id']}")
                        if unk_vol:
                            recon_vol = None
                    with recol4:
                        unk_temp = st.checkbox("Unk", key=f"unk_recon_temp_{step['id']}")
                        recon_temp = st.number_input("Temp (°C)", 0.0, 50.0, 4.0, 1.0,
                                                     disabled=unk_temp, key=f"recon_temp_{step['id']}")
                        if unk_temp:
                            recon_temp = None
                    
                    # Auto-calculate concentration
                    final_conc = None
                    if lyoph_wt and recon_vol and lyoph_wt > 0 and recon_vol > 0:
                        final_conc = lyoph_wt / recon_vol
                        st.success(f"✅ **Stock concentration: {final_conc:.2f} mg/mL**")
                    
                    notes = st.text_input("Notes", placeholder="e.g., with pepsin 0.1 mg/mL, stirred overnight",
                                         key=f"recon_notes_{step['id']}")
                    
                    processing_steps.append({
                        "type": "reconstitute",
                        "solvent": solvent,
                        "lyoph_weight_mg": lyoph_wt,
                        "recon_volume_mL": recon_vol,
                        "final_conc_mgml": final_conc,
                        "temp_C": recon_temp,
                        "notes": notes or None
                    })
                
                elif step["type"] == "decell":
                    st.caption("💡 Decellularization: Remove cells while preserving ECM structure")
                    
                    dcol1, dcol2, dcol3, dcol4 = st.columns(4)
                    with dcol1:
                        reagent_sel = st.selectbox("Reagent", DECELL_AGENTS, key=f"decell_reag_sel_batch_{step['id']}")
                        if reagent_sel == "Other":
                            reagent = st.text_input("Specify reagent", placeholder="e.g., custom detergent", key=f"decell_reag_other_batch_{step['id']}")
                        else:
                            reagent = reagent_sel
                    with dcol2:
                        unk_conc = st.checkbox("Unk", key=f"unk_decell_conc_batch_{step['id']}", help="Unknown/not reported")
                        conc_val = st.number_input("Concentration", 0.0, 100.0, 1.0, 0.1, disabled=unk_conc, key=f"decell_conc_batch_{step['id']}")
                        conc_unit = st.selectbox("Units", ["%","M","mM","mg/mL","v/v"], disabled=unk_conc, key=f"decell_unit_batch_{step['id']}")
                        if unk_conc:
                            conc_val, conc_unit = None, None
                    with dcol3:
                        unk_dur = st.checkbox("Unk", key=f"unk_decell_dur_batch_{step['id']}", help="Unknown/not reported")
                        duration = st.number_input("Duration (hours)", 0.0, 1000.0, 24.0, 0.5, disabled=unk_dur, key=f"decell_dur_batch_{step['id']}")
                        if unk_dur:
                            duration = None
                        unk_temp = st.checkbox("Unk", key=f"unk_decell_temp_batch_{step['id']}", help="Unknown/not reported")
                        temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, disabled=unk_temp, key=f"decell_temp_batch_{step['id']}", 
                                              help="e.g., 4°C (fridge), 22°C (room temp), 37°C")
                        if unk_temp:
                            temp = None
                    with dcol4:
                        unk_chg = st.checkbox("Unk", key=f"unk_decell_chg_batch_{step['id']}", help="Unknown/not reported")
                        changes = st.number_input("# Changes", 1, 100, 3, 1, disabled=unk_chg, key=f"decell_chg_batch_{step['id']}", 
                                                 help="Solution changes")
                        if unk_chg:
                            changes = None
                    
                    notes = st.text_input("Notes (optional)", placeholder="e.g., gentle agitation, sterile conditions", key=f"decell_notes_batch_{step['id']}")
                    
                    processing_steps.append({
                        "type": "decell", 
                        "reagent": reagent, 
                        "concentration": conc_val, 
                        "conc_units": conc_unit, 
                        "duration_hours": duration, 
                        "temp_C": temp, 
                        "changes": changes, 
                        "notes": notes or None
                    })
                    
                    # Remove button for this specific step
                    if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"):
                        st.session_state.batch_proc_steps.pop(i)
                        st.rerun()
                
                elif step["type"] == "wash":
                    st.caption("💡 Washing: Remove decellularization agents and cellular debris")
                    
                    wcol1, wcol2, wcol3, wcol4 = st.columns(4)
                    with wcol1:
                        solution_sel = st.selectbox("Solution", COMMON_BUFFERS + ["DI water"], key=f"wash_sol_sel_batch_{step['id']}")
                        if solution_sel == "Other":
                            solution = st.text_input("Specify solution", placeholder="e.g., custom buffer", key=f"wash_sol_other_batch_{step['id']}")
                        else:
                            solution = solution_sel
                    with wcol2:
                        conc_val = st.number_input("Conc", 0.0, 100.0, 1.0, 0.1, key=f"wash_conc_batch_{step['id']}")
                        conc_unit = st.selectbox("Units", ["x","M","mM","%","n/a"], key=f"wash_unit_batch_{step['id']}")
                    with wcol3:
                        washes = st.number_input("# Washes", 1, 20, 3, 1, key=f"wash_num_batch_{step['id']}")
                        duration = st.number_input("Duration each (min)", 0.0, 500.0, 15.0, 5.0, key=f"wash_dur_batch_{step['id']}")
                    with wcol4:
                        temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"wash_temp_batch_{step['id']}", 
                                              help="Wash temperature")
                    
                    notes = st.text_input("Notes (optional)", placeholder="e.g., shaking, flow rate", key=f"wash_notes_batch_{step['id']}")
                    
                    processing_steps.append({
                        "type": "wash", 
                        "solution": solution, 
                        "concentration": conc_val, 
                        "conc_units": conc_unit, 
                        "n_washes": washes, 
                        "duration_min": duration, 
                        "temp_C": temp, 
                        "notes": notes or None
                    })
                    
                    # Remove button for this specific step
                    if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"):
                        st.session_state.batch_proc_steps.pop(i)
                        st.rerun()
                
                elif step["type"] == "delipid":
                    st.caption("💡 Delipidation: Remove lipids and fat content")
                    
                    dlcol1, dlcol2, dlcol3, dlcol4 = st.columns(4)
                    with dlcol1:
                        solvent_sel = st.selectbox("Solvent", DELIPID_SOLVENTS, key=f"delip_solv_sel_batch_{step['id']}")
                        if solvent_sel == "Other":
                            solvent = st.text_input("Specify solvent", placeholder="e.g., custom solvent", key=f"delip_solv_other_batch_{step['id']}")
                        else:
                            solvent = solvent_sel
                    with dlcol2:
                        conc_val = st.number_input("Concentration", 0.0, 100.0, 100.0, 1.0, key=f"delip_conc_batch_{step['id']}")
                        conc_unit = st.selectbox("Units", ["%","v/v"], key=f"delip_unit_batch_{step['id']}")
                    with dlcol3:
                        duration = st.number_input("Duration (hours)", 0.0, 100.0, 2.0, 0.25, key=f"delip_dur_batch_{step['id']}")
                        temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"delip_temp_batch_{step['id']}", 
                                              help="Room temp, fridge, etc.")
                    with dlcol4:
                        times = st.number_input("# Times", 1, 20, 3, 1, key=f"delip_times_batch_{step['id']}", 
                                               help="Number of repetitions")
                    
                    notes = st.text_input("Notes (optional)", placeholder="e.g., vortex, solvent grade", key=f"delip_notes_batch_{step['id']}")
                    
                    processing_steps.append({
                        "type": "delipid", 
                        "solvent": solvent, 
                        "concentration": conc_val, 
                        "conc_units": conc_unit, 
                        "duration_hours": duration, 
                        "temp_C": temp, 
                        "n_times": times, 
                        "notes": notes or None
                    })
                    
                    # Remove button for this specific step
                    if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"):
                        st.session_state.batch_proc_steps.pop(i)
                        st.rerun()
                
                elif step["type"] == "enzyme":
                    st.caption("💡 Enzyme treatment: Digest specific ECM components")
                    
                    ecol1, ecol2, ecol3, ecol4 = st.columns(4)
                    with ecol1:
                        enzyme_sel = st.selectbox("Enzyme", COMMON_ENZYMES, key=f"enz_name_sel_batch_{step['id']}")
                        if enzyme_sel == "Other":
                            enzyme = st.text_input("Specify enzyme", placeholder="e.g., custom enzyme", key=f"enz_name_other_batch_{step['id']}")
                        else:
                            enzyme = enzyme_sel
                    with ecol2:
                        conc = st.number_input("Conc.", 0.0, 100.0, 1.0, 0.1, key=f"enz_conc_batch_{step['id']}")
                        units = st.selectbox("Units", ["mg/mL", "U/mL", "mg/g"], key=f"enz_units_batch_{step['id']}")
                    with ecol3:
                        duration = st.number_input("Duration (hrs)", 0.0, 100.0, 2.0, 0.25, key=f"enz_dur_batch_{step['id']}")
                        temp = st.number_input("Temp (°C)", 4.0, 60.0, 37.0, 1.0, key=f"enz_temp_batch_{step['id']}")
                    with ecol4:
                        ph_val = st.number_input("pH", 1.0, 14.0, 7.4, 0.1, key=f"enz_ph_batch_{step['id']}")
                        buffer = st.text_input("Buffer", placeholder="e.g., PBS, Tris", key=f"enz_buffer_batch_{step['id']}")
                    
                    notes = st.text_input("Notes (optional)", placeholder="e.g., gentle agitation, sterile conditions", key=f"enz_notes_batch_{step['id']}")
                    
                    processing_steps.append({
                        "type": "enzyme", 
                        "enzyme": enzyme, 
                        "concentration": conc, 
                        "units": units, 
                        "duration_hours": duration, 
                        "temp_C": temp, 
                        "pH": ph_val, 
                        "buffer": buffer, 
                        "notes": notes or None
                    })
                    
                    # Remove button for this specific step
                    if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"):
                        st.session_state.batch_proc_steps.pop(i)
                        st.rerun()
                
                elif step["type"] == "homogenize":
                    st.caption("💡 Homogenization: Mechanical tissue disruption")
                    
                    hcol1, hcol2, hcol3, hcol4 = st.columns(4)
                    with hcol1:
                        medium = st.selectbox("Medium/Liquid", COMMON_BUFFERS + COMMON_DILUENTS + ["PBS", "Saline", "DI water", "Other"], key=f"homog_medium_batch_{step['id']}")
                        if medium == "Other":
                            medium = st.text_input("Specify medium", placeholder="e.g., 0.1M HCl", key=f"homog_medium_other_batch_{step['id']}")
                    with hcol2:
                        rpm = st.number_input("RPM", 0, 50000, 10000, 1000, key=f"homog_rpm_batch_{step['id']}")
                        duration = st.number_input("Duration (min)", 0.0, 500.0, 5.0, 1.0, key=f"homog_dur_batch_{step['id']}")
                    with hcol3:
                        temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"homog_temp_batch_{step['id']}")
                        passes = st.number_input("# Passes", 1, 20, 1, 1, key=f"homog_passes_batch_{step['id']}")
                    with hcol4:
                        volume = st.number_input("Volume (mL)", 0.0, 1000.0, 10.0, 1.0, key=f"homog_vol_batch_{step['id']}")
                        ratio = st.text_input("Tissue:Medium ratio", placeholder="e.g., 1:10, 1:20", key=f"homog_ratio_batch_{step['id']}")
                    
                    notes = st.text_input("Notes (optional)", placeholder="e.g., sterile conditions, ice bath", key=f"homog_notes_batch_{step['id']}")
                    processing_steps.append({"type": "homogenize", "medium": medium, "rpm": rpm, "duration_min": duration, "temp_C": temp, "passes": passes, "volume_mL": volume, "tissue_medium_ratio": ratio, "notes": notes or None})
                    
                    # Remove button for this specific step
                    if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"):
                        st.session_state.batch_proc_steps.pop(i)
                        st.rerun()
                
                elif step["type"] == "grind":
                    st.caption("💡 Grinding/Milling: Mechanical particle size reduction")
                    
                    gcol1, gcol2, gcol3, gcol4 = st.columns(4)
                    with gcol1:
                        method = st.selectbox("Method", ["mortar_pestle", "ball_mill", "cryomill", "other"], key=f"grind_method_batch_{step['id']}")
                        if method == "other":
                            method = st.text_input("Specify method", key=f"grind_method_other_batch_{step['id']}")
                    with gcol2:
                        duration = st.number_input("Duration (min)", 0.0, 500.0, 5.0, 1.0, key=f"grind_dur_batch_{step['id']}")
                    with gcol3:
                        temp = st.number_input("Temp (°C)", -200.0, 50.0, 4.0, 1.0, key=f"grind_temp_batch_{step['id']}")
                    with gcol4:
                        cycles = st.number_input("# Cycles", 1, 50, 1, 1, key=f"grind_cycles_batch_{step['id']}")
                    
                    notes = st.text_input("Notes (optional)", placeholder="e.g., liquid nitrogen, sterile", key=f"grind_notes_batch_{step['id']}")
                    processing_steps.append({"type": "grind", "method": method, "duration_min": duration, "temp_C": temp, "cycles": cycles, "notes": notes or None})
                    
                    # Remove button for this specific step
                    if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"):
                        st.session_state.batch_proc_steps.pop(i)
                        st.rerun()
                
                elif step["type"] == "freeze_thaw":
                    st.caption("💡 Freeze-Thaw: Cell lysis and ECM disruption")
                    
                    ftcol1, ftcol2, ftcol3, ftcol4 = st.columns(4)
                    with ftcol1:
                        cycles = st.number_input("# Cycles", 1, 50, 3, 1, key=f"ft_cycles_batch_{step['id']}")
                    with ftcol2:
                        freeze_temp = st.number_input("Freeze temp (°C)", -200.0, 0.0, -80.0, 10.0, key=f"ft_ftemp_batch_{step['id']}")
                    with ftcol3:
                        thaw_temp = st.number_input("Thaw temp (°C)", 0.0, 50.0, 37.0, 1.0, key=f"ft_ttemp_batch_{step['id']}")
                    with ftcol4:
                        duration_cycle = st.number_input("Duration/cycle (min)", 0.0, 1000.0, 60.0, 5.0, key=f"ft_dur_batch_{step['id']}")
                    
                    notes = st.text_input("Notes (optional)", placeholder="e.g., liquid nitrogen, water bath", key=f"ft_notes_batch_{step['id']}")
                    processing_steps.append({"type": "freeze_thaw", "cycles": cycles, "freeze_temp_C": freeze_temp, "thaw_temp_C": thaw_temp, "duration_min": duration_cycle, "notes": notes or None})
                    
                    # Remove button for this specific step
                    if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"):
                        st.session_state.batch_proc_steps.pop(i)
                        st.rerun()
                
                elif step["type"] == "lyophilize":
                    st.caption("💡 Lyophilization: Freeze-drying for storage")
                    
                    lycol1, lycol2, lycol3, lycol4 = st.columns(4)
                    with lycol1:
                        unk_lyoph_dur = st.checkbox("Unk", key=f"unk_lyoph_dur_batch_{step['id']}", help="Unknown/not reported")
                        duration = st.number_input("Duration (hours)", 0.0, 200.0, 48.0, 1.0, disabled=unk_lyoph_dur, key=f"lyoph_dur_batch_{step['id']}")
                        if unk_lyoph_dur:
                            duration = None
                    with lycol2:
                        temp = st.number_input("Temp (°C)", -100.0, 0.0, -50.0, 5.0, key=f"lyoph_temp_batch_{step['id']}")
                    with lycol3:
                        unk_press = st.checkbox("Unk", key=f"unk_lyoph_press_batch_{step['id']}", help="Unknown/not reported")
                        pressure = st.number_input("Pressure (mTorr)", 0.0, 1000.0, 100.0, 10.0, disabled=unk_press, key=f"lyoph_press_batch_{step['id']}")
                        if unk_press:
                            pressure = None
                    with lycol4:
                        shelf_temp = st.number_input("Shelf temp (°C)", -100.0, 50.0, 20.0, 5.0, key=f"lyoph_shelf_batch_{step['id']}")
                    
                    notes = st.text_input("Notes (optional)", placeholder="e.g., pre-freeze rate, condenser temp", key=f"lyoph_notes_batch_{step['id']}")
                    processing_steps.append({"type": "lyophilize", "duration_hours": duration, "temp_C": temp, "pressure_mtorr": pressure, "shelf_temp_C": shelf_temp, "notes": notes or None})
                    
                    # Remove button for this specific step
                    if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"):
                        st.session_state.batch_proc_steps.pop(i)
                        st.rerun()
                
                elif step["type"] == "ph_adjust":
                    st.caption("💡 pH Adjustment: Neutralization and buffering")
                    
                    phcol1, phcol2, phcol3, phcol4 = st.columns(4)
                    with phcol1:
                        direction = st.radio("Direction", ["Raise pH (base)", "Lower pH (acid)"], key=f"ph_dir_batch_{step['id']}", horizontal=True)
                        if "base" in direction.lower():
                            reagent_sel = st.selectbox("Base", COMMON_BASES, key=f"ph_base_sel_batch_{step['id']}")
                        else:
                            reagent_sel = st.selectbox("Acid", COMMON_ACIDS, key=f"ph_acid_sel_batch_{step['id']}")
                        if reagent_sel == "Other":
                            reagent = st.text_input("Specify reagent", key=f"ph_reag_other_batch_{step['id']}")
                        else:
                            reagent = reagent_sel
                    with phcol2:
                        conc_val = st.number_input("Concentration", 0.0, 10.0, 1.0, 0.1, key=f"ph_conc_batch_{step['id']}")
                        conc_unit = st.selectbox("Units", ["M", "mM", "%"], key=f"ph_unit_batch_{step['id']}")
                    with phcol3:
                        target_ph = st.number_input("Target pH", 1.0, 14.0, 7.4, 0.1, key=f"ph_target_batch_{step['id']}")
                        final_ph = st.number_input("Final pH", 1.0, 14.0, 7.4, 0.1, key=f"ph_final_batch_{step['id']}")
                    with phcol4:
                        temp = st.number_input("Temp (°C)", 0.0, 50.0, 22.0, 1.0, key=f"ph_temp_batch_{step['id']}")
                        duration = st.number_input("Duration (min)", 0.0, 300.0, 15.0, 5.0, key=f"ph_dur_batch_{step['id']}")
                    
                    notes = st.text_input("Notes (optional)", placeholder="e.g., dropwise addition, monitoring", key=f"ph_notes_batch_{step['id']}")
                    processing_steps.append({"type": "ph_adjust", "direction": direction, "reagent": reagent, "concentration": conc_val, "conc_units": conc_unit, "target_pH": target_ph, "final_pH": final_ph, "temp_C": temp, "duration_min": duration, "notes": notes or None})
                    
                    # Remove button for this specific step
                    if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"):
                        st.session_state.batch_proc_steps.pop(i)
                        st.rerun()
                
                elif step["type"] == "dialysis":
                    st.caption("💡 Dialysis: Buffer exchange and purification")
                    
                    diacol1, diacol2, diacol3, diacol4 = st.columns(4)
                    with diacol1:
                        buffer_sel = st.selectbox("Buffer/Solution", COMMON_BUFFERS + COMMON_ACIDS, key=f"dial_buf_sel_batch_{step['id']}")
                        if buffer_sel == "Other":
                            buffer = st.text_input("Specify buffer", key=f"dial_buf_other_batch_{step['id']}")
                        else:
                            buffer = buffer_sel
                    with diacol2:
                        conc_val = st.number_input("Concentration", 0.0, 100.0, 1.0, 0.1, key=f"dial_conc_batch_{step['id']}")
                        conc_unit = st.selectbox("Units", ["x", "M", "mM"], key=f"dial_unit_batch_{step['id']}")
                    with diacol3:
                        duration = st.number_input("Duration (hours)", 0.0, 168.0, 24.0, 1.0, key=f"dial_dur_batch_{step['id']}")
                        changes = st.number_input("# Changes", 1, 20, 3, 1, key=f"dial_changes_batch_{step['id']}")
                    with diacol4:
                        temp = st.number_input("Temp (°C)", 0.0, 50.0, 4.0, 1.0, key=f"dial_temp_batch_{step['id']}")
                        mwco = st.number_input("MWCO (kDa)", 1.0, 100.0, 10.0, 1.0, key=f"dial_mwco_batch_{step['id']}")
                    
                    notes = st.text_input("Notes (optional)", placeholder="e.g., stirring, sterile conditions", key=f"dial_notes_batch_{step['id']}")
                    processing_steps.append({"type": "dialysis", "buffer": buffer, "concentration": conc_val, "conc_units": conc_unit, "duration_hours": duration, "changes": changes, "temp_C": temp, "mwco_kda": mwco, "notes": notes or None})
                    
                    # Remove button for this specific step
                    if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"):
                        st.session_state.batch_proc_steps.pop(i)
                        st.rerun()
                
                elif step["type"] == "storage":
                    st.caption("💡 Storage: Preservation conditions")
                    
                    scol1, scol2, scol3, scol4 = st.columns(4)
                    with scol1:
                        temp = st.number_input("Temp (°C)", -200.0, 50.0, -80.0, 1.0, key=f"stor_temp_batch_{step['id']}")
                    with scol2:
                        duration = st.text_input("Duration", placeholder="e.g., 7 days, 3 months", key=f"stor_dur_batch_{step['id']}")
                    with scol3:
                        container = st.selectbox("Container", ["tube", "vial", "bag", "plate", "other"], key=f"stor_container_batch_{step['id']}")
                    with scol4:
                        atmosphere = st.selectbox("Atmosphere", ["air", "nitrogen", "vacuum", "argon"], key=f"stor_atmo_batch_{step['id']}")
                    
                    notes = st.text_input("Notes (optional)", placeholder="e.g., sterile, labeled", key=f"stor_notes_batch_{step['id']}")
                    processing_steps.append({"type": "storage", "temp_C": temp, "duration": duration, "container": container, "atmosphere": atmosphere, "notes": notes or None})
                    
                    # Remove button for this specific step
                    if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"):
                        st.session_state.batch_proc_steps.pop(i)
                        st.rerun()
                
                elif step["type"] == "filtration":
                    st.caption("💡 Filtration: Size-based separation")
                    
                    fcol1, fcol2, fcol3, fcol4 = st.columns(4)
                    with fcol1:
                        filter_type = st.selectbox("Filter type", ["spin_filter", "syringe_filter", "vacuum_filter", "gravity_filter", "other"], key=f"filt_type_batch_{step['id']}")
                        if filter_type == "other":
                            filter_type = st.text_input("Specify type", key=f"filt_type_other_batch_{step['id']}")
                    with fcol2:
                        pore_size = st.number_input("Pore size (µm)", 0.1, 100.0, 0.22, 0.01, key=f"filt_pore_batch_{step['id']}")
                        material = st.selectbox("Material", ["PES", "PVDF", "cellulose", "nylon", "other"], key=f"filt_material_batch_{step['id']}")
                    with fcol3:
                        pressure = st.number_input("Pressure (psi)", 0.0, 100.0, 5.0, 0.5, key=f"filt_press_batch_{step['id']}")
                        duration = st.number_input("Duration (min)", 0.0, 300.0, 10.0, 1.0, key=f"filt_dur_batch_{step['id']}")
                    with fcol4:
                        temp = st.number_input("Temp (°C)", 0.0, 50.0, 22.0, 1.0, key=f"filt_temp_batch_{step['id']}")
                        volume = st.number_input("Volume (mL)", 0.0, 1000.0, 10.0, 1.0, key=f"filt_vol_batch_{step['id']}")
                    
                    notes = st.text_input("Notes (optional)", placeholder="e.g., pre-wet, sterile", key=f"filt_notes_batch_{step['id']}")
                    processing_steps.append({"type": "filtration", "filter_type": filter_type, "pore_size_um": pore_size, "material": material, "pressure_psi": pressure, "duration_min": duration, "temp_C": temp, "volume_mL": volume, "notes": notes or None})
                    
                    # Remove button for this specific step
                    if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"):
                        st.session_state.batch_proc_steps.pop(i)
                        st.rerun()
                
                elif step["type"] == "centrifuge":
                    st.caption("💡 Centrifugation: Density-based separation")
                    
                    ccol1, ccol2, ccol3, ccol4 = st.columns(4)
                    with ccol1:
                        purpose = st.selectbox("Purpose", ["clarification", "concentration", "pellet_removal", "debris_removal", "other"], key=f"cent_purp_batch_{step['id']}")
                        if purpose == "other":
                            purpose = st.text_input("Specify purpose", key=f"cent_purp_other_batch_{step['id']}")
                    with ccol2:
                        speed = st.number_input("Speed (RCF)", 0, 50000, 3000, 100, key=f"cent_speed_batch_{step['id']}")
                        duration = st.number_input("Duration (min)", 0.0, 300.0, 10.0, 1.0, key=f"cent_dur_batch_{step['id']}")
                    with ccol3:
                        temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"cent_temp_batch_{step['id']}")
                        cycles = st.number_input("# Cycles", 1, 10, 1, 1, key=f"cent_cycles_batch_{step['id']}")
                    with ccol4:
                        volume = st.number_input("Volume (mL)", 0.0, 1000.0, 50.0, 5.0, key=f"cent_vol_batch_{step['id']}")
                        tube_type = st.selectbox("Tube type", ["microcentrifuge", "conical", "round_bottom", "other"], key=f"cent_tube_batch_{step['id']}")
                    
                    notes = st.text_input("Notes (optional)", placeholder="e.g., brake on/off, sterile", key=f"cent_notes_batch_{step['id']}")
                    processing_steps.append({"type": "centrifuge", "purpose": purpose, "speed_rcf": speed, "duration_min": duration, "temp_C": temp, "cycles": cycles, "volume_mL": volume, "tube_type": tube_type, "notes": notes or None})
                    
                    # Remove button for this specific step
                    if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"):
                        st.session_state.batch_proc_steps.pop(i)
                        st.rerun()
                
                # For other step types, provide basic form
                else:
                    notes = st.text_input("Notes", placeholder=f"Describe {step['type']} process", key=f"step_notes_{step['id']}")
                    processing_steps.append({
                        "type": step["type"],
                        "notes": notes or None
                    })
                    
                    # Remove button for this specific step
                    if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"):
                        st.session_state.batch_proc_steps.pop(i)
                        st.rerun()
    
    else:
        st.info("ℹ️ Commercial products: Processing protocol N/A")
        processing_steps = []
    
    st.markdown("---")
    
    # ========== BATCH CHARACTERIZATION ==========
    st.subheader("📊 Batch Characterization")
    st.caption("Measure ECM batch properties (can add later)")
    
    with st.expander("Characterization Measurements", expanded=False):
        char1, char2, char3 = st.columns(3)
        with char1:
            unk_protein = st.checkbox("Unk", key="batch_unk_protein", help="Unknown/not measured")
            ecm_total_protein_mgml = st.number_input("Protein (mg/mL)", 0.0, 100.0, 0.0, 0.1, disabled=unk_protein)
            if unk_protein:
                ecm_total_protein_mgml = None
            protein_assay_method = st.selectbox("Assay Method", 
                ["","BCA","Bradford","Lowry","DC_assay","A280","other"], disabled=unk_protein)
        with char2:
            unk_ph = st.checkbox("Unk", key="batch_unk_ph", help="Unknown/not measured")
            pre_pH = st.number_input("Pre-pH", 0.0, 14.0, 0.0, 0.1, disabled=unk_ph,
                                    help="pH before neutralization")
            if unk_ph:
                pre_pH = None
            
            unk_cond = st.checkbox("Unk", key="batch_unk_cond", help="Unknown/not measured")
            pre_conductivity_mS = st.number_input("Pre-Conductivity (mS/cm)", 0.0, 100.0, 0.0, 0.1, disabled=unk_cond)
            if unk_cond:
                pre_conductivity_mS = None
        with char3:
            unk_uv = st.checkbox("Unk", key="batch_unk_uv", help="Unknown/not measured")
            uv_A220 = st.number_input("UV A220", 0.0, 1e6, 0.0, 0.01, disabled=unk_uv)
            uv_A280 = st.number_input("UV A280", 0.0, 1e6, 0.0, 0.01, disabled=unk_uv)
            if unk_uv:
                uv_A220 = None
                uv_A280 = None
        
        # Auto-calculate UV ratio
        uv_ratio = None
        if uv_A220 and uv_A280 and uv_A220 > 0 and uv_A280 > 0:
            uv_ratio = uv_A220 / uv_A280
            st.info(f"📊 UV ratio A220/A280: **{uv_ratio:.3f}**")
    
    st.markdown("---")
    
    # ========== NOTES ==========
    notes_ecm_processing = st.text_area(
        "📝 ECM Processing Notes",
        placeholder="e.g., Tissue was slightly fibrous, decell took longer than usual, final solution clear",
        help="Notes about ECM preparation and characterization",
        height=100
    )
    
    st.markdown("---")
    
    # ========== SAVE BUTTON ==========
    if st.button("💾 Save ECM Batch", type="primary", use_container_width=True):
        # Validation
        errors = []
        if not operator_id:
            errors.append("Operator ID required")
        
        # Family required for lab-made, optional for commercial
        if not is_commercial and not family:
            errors.append("ECM Family required (or check Commercial Product)")
        
        if not batch_id:
            errors.append("Batch ID required (fill in required fields)")
        
        # Species/tissue only required for lab-made decECM (commercial may not disclose)
        if family == "decECM" and not is_commercial:
            if not dec_species:
                errors.append("Species required for lab-made decECM")
            if not dec_tissue:
                errors.append("Tissue required for lab-made decECM")
        
        if errors:
            for e in errors:
                st.error(f"❌ {e}")
            return
        
        # Prepare payload
        payload = {
            'batch_id': batch_id,
            'date': date_input.isoformat(),
            'operator_id': operator_id,
            'family': family,
            'is_commercial_product': int(is_commercial) if is_commercial else 0,
            'commercial_vendor': vendor if is_commercial else None,
            'commercial_product_name': (custom_product or product_name) if is_commercial else None,
            'commercial_catalog_number': catalog_num if is_commercial else None,
            'commercial_lot_number': lot_num if is_commercial else None,
            'commercial_website': website if is_commercial else None,
            'ecm_origin_species': dec_species or None,
            'ecm_source_tissue': dec_tissue or None,
            'collagen_type': collagen_type or None,
            'pre_storage_days_4C': pre_storage_days_4C,
            'pre_storage_fresh_notes': pre_storage_fresh_notes or None,
            'pre_storage_freeze_cycles': pre_storage_freeze_cycles if 'pre_storage_freeze_cycles' in locals() else None,
            'pre_storage_temp_freezer': pre_storage_temp_freezer,
            'pre_storage_duration_months': pre_storage_duration_months,
            'pre_storage_frozen_in': pre_storage_frozen_in or None,
            'pre_storage_thaw_method': pre_storage_thaw_method if 'pre_storage_thaw_method' in locals() else None,
            'pre_storage_thaw_duration_min': pre_storage_thaw_duration_min if 'pre_storage_thaw_duration_min' in locals() else None,
            'pre_storage_ft_notes': pre_storage_ft_notes if 'pre_storage_ft_notes' in locals() else None,
            'processing_protocol': json.dumps(processing_steps) if processing_steps else None,
            'ecm_total_protein_mgml': ecm_total_protein_mgml if ecm_total_protein_mgml > 0 else None,
            'protein_assay_method': protein_assay_method or None,
            'pre_pH': pre_pH if pre_pH > 0 else None,
            'pre_conductivity_mS': pre_conductivity_mS if pre_conductivity_mS > 0 else None,
            'uv_A220': uv_A220 if uv_A220 > 0 else None,
            'uv_A280': uv_A280 if uv_A280 > 0 else None,
            'uv_ratio_A220_A280': uv_ratio,
            'notes_pre': notes_ecm_processing or None,  # Using notes_pre for ECM processing
            'created_at': datetime.now().isoformat(),
            'updated_at': datetime.now().isoformat()
        }
        
        # Save to database
        try:
            # Create batches table if it doesn't exist
            conn = sqlite3.connect(DB_PATH)
            conn.execute("""
                CREATE TABLE IF NOT EXISTS ecm_batches_lab (
                    batch_id TEXT PRIMARY KEY,
                    operator_id TEXT,
                    family TEXT,
                    species TEXT,
                    tissue TEXT,
                    source_description TEXT,
                    commercial_product TEXT,
                    processing_steps TEXT,  -- JSON string
                    characterization TEXT,  -- JSON string
                    created_at TEXT,
                    updated_at TEXT
                )
            """)
            
            # Prepare characterization data
            characterization = {
                'ecm_total_protein_mgml': payload.get('ecm_total_protein_mgml'),
                'protein_assay_method': payload.get('protein_assay_method'),
                'pre_pH': payload.get('pre_pH'),
                'pre_conductivity_mS': payload.get('pre_conductivity_mS'),
                'uv_A220': payload.get('uv_A220'),
                'uv_A280': payload.get('uv_A280'),
                'uv_ratio_A220_A280': payload.get('uv_ratio_A220_A280'),
                'pre_storage_days_4C': payload.get('pre_storage_days_4C'),
                'pre_storage_temp_freezer': payload.get('pre_storage_temp_freezer'),
                'pre_storage_duration_months': payload.get('pre_storage_duration_months'),
                'pre_storage_fresh_notes': payload.get('pre_storage_fresh_notes'),
                'pre_storage_frozen_in': payload.get('pre_storage_frozen_in'),
                'pre_storage_thaw_method': payload.get('pre_storage_thaw_method'),
                'pre_storage_thaw_duration_min': payload.get('pre_storage_thaw_duration_min'),
                'pre_storage_ft_notes': payload.get('pre_storage_ft_notes'),
                'notes_pre': payload.get('notes_pre')
            }
            
            # Insert batch record using actual form variables
            batch_data = {
                'batch_id': batch_id,
                'operator_id': operator_id,
                'family': family,
                'species': dec_species if family == 'decECM' else None,
                'tissue': dec_tissue if family == 'decECM' else None,
                'source_description': f"{family} from {dec_species} {dec_tissue}" if family == 'decECM' and dec_species and dec_tissue else None,
                'commercial_product': f"{vendor}: {custom_product or product_name}" if is_commercial else None,
                'processing_steps': json.dumps(processing_steps),
                'characterization': json.dumps(characterization),
                'created_at': datetime.now().isoformat(),
                'updated_at': datetime.now().isoformat()
            }
            
            # Debug: Show what we're trying to save
            st.write("🔍 Debug - Batch data being saved:")
            st.json(batch_data)
            
            conn.execute("""
                INSERT OR REPLACE INTO ecm_batches_lab 
                (batch_id, operator_id, family, species, tissue, source_description, 
                 commercial_product, processing_steps, characterization, created_at, updated_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """, (
                batch_data['batch_id'], batch_data['operator_id'], batch_data['family'],
                batch_data['species'], batch_data['tissue'], batch_data['source_description'],
                batch_data['commercial_product'], batch_data['processing_steps'],
                batch_data['characterization'], batch_data['created_at'], batch_data['updated_at']
            ))
            
            conn.commit()
            conn.close()
            
            st.success(f"✅ **ECM Batch Created and Saved!**")
            st.success(f"📦 Batch ID: **{batch_id}**")
            st.info("➡️ Go to **Gelation Experiments** to test this batch on plates")
            st.info("📚 Go to **Batch Library** to view all your created batches")
            
            # Clear form
            st.session_state.batch_proc_steps = []
            st.balloons()
            
        except Exception as e:
            st.error(f"❌ Error saving batch: {e}")
            import traceback
            with st.expander("Error Details"):
                st.code(traceback.format_exc())

# ============================================================================
# MAIN
# ============================================================================

def main():
    st.set_page_config(page_title="ECM Batch Creation", page_icon="🧬", layout="wide")
    
    # Load codebook
    codebook = {
        'family': ["collagen", "decECM", "fibrin", "alginate", "gelMA", "gelatin", "hyaluronan", "PEG_DA", "composite", "other"],
        'species': ["human", "porcine", "bovine", "rat", "mouse", "avian", "other"],
        'tissues': ["mammary", "dermis", "small_intestine_submucosa", "myocardium", "pericardium",
                   "liver", "lung", "kidney", "bladder", "tendon", "cartilage", "meniscus", 
                   "adipose", "placenta", "amniotic_membrane", "esophagus", "cornea", "other"]
    }
    
    show_batch_creation_form(codebook)

if __name__ == "__main__":
    main()