cập nhật animation hiển thị modal, call API edit

This commit is contained in:
2025-12-22 22:47:08 +07:00
parent 67e9fc22a3
commit afc6acbfe2
16 changed files with 530 additions and 216 deletions

View File

@@ -0,0 +1,388 @@
import React, { useState } from "react";
import {
View,
Text,
TouchableOpacity,
StyleSheet,
Modal,
Platform,
ScrollView,
TextInput,
ActivityIndicator,
Alert,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useThings } from "@/state/use-thing";
import { useI18n } from "@/hooks/use-i18n";
import { useThemeContext } from "@/hooks/use-theme-context";
import { queryLastTrip } from "@/controller/TripController";
import { showErrorToast } from "@/services/toast_service";
interface AutoFillSectionProps {
onAutoFill: (tripData: Model.Trip, selectedThingId: string) => void;
}
export default function AutoFillSection({ onAutoFill }: AutoFillSectionProps) {
const { t } = useI18n();
const { colors } = useThemeContext();
const [isOpen, setIsOpen] = useState(false);
const [searchText, setSearchText] = useState("");
const [isLoading, setIsLoading] = useState(false);
const { things } = useThings();
// Convert things to ship options
const shipOptions =
things
?.filter((thing) => thing.id != null)
.map((thing) => ({
thingId: thing.id as string,
shipName: thing.metadata?.ship_name || "",
})) || [];
// Filter ships based on search text
const filteredShips = shipOptions.filter((ship) => {
const searchLower = searchText.toLowerCase();
return ship.shipName.toLowerCase().includes(searchLower);
});
const handleSelectShip = async (thingId: string) => {
setIsLoading(true);
try {
const response = await queryLastTrip(thingId);
if (response.data) {
// Close the modal first before showing alert
setIsOpen(false);
setSearchText("");
// Pass thingId along with trip data for filling ShipSelector
onAutoFill(response.data, thingId);
// Use Alert instead of Toast so it appears above all modals
Alert.alert(
t("common.success"),
t("diary.autoFill.success")
);
} else {
showErrorToast(t("diary.autoFill.noData"));
}
} catch (error) {
console.error("Error fetching last trip:", error);
showErrorToast(t("diary.autoFill.error"));
} finally {
setIsLoading(false);
}
};
const themedStyles = {
container: {
backgroundColor: colors.backgroundSecondary,
borderColor: colors.primary,
},
label: { color: colors.text },
description: { color: colors.textSecondary },
button: {
backgroundColor: colors.primary,
},
modalContent: { backgroundColor: colors.card },
searchContainer: {
backgroundColor: colors.backgroundSecondary,
borderColor: colors.border,
},
searchInput: { color: colors.text },
option: { borderBottomColor: colors.separator },
optionText: { color: colors.text },
emptyText: { color: colors.textSecondary },
};
return (
<View style={[styles.container, themedStyles.container]}>
<View style={styles.contentWrapper}>
<View style={styles.iconContainer}>
<Ionicons name="flash" size={24} color={colors.primary} />
</View>
<View style={styles.textContainer}>
<Text style={[styles.label, themedStyles.label]}>
{t("diary.autoFill.title")}
</Text>
<Text style={[styles.description, themedStyles.description]}>
{t("diary.autoFill.description")}
</Text>
</View>
</View>
<TouchableOpacity
style={[styles.button, themedStyles.button]}
onPress={() => setIsOpen(true)}
activeOpacity={0.7}
>
<Text style={styles.buttonText}>{t("diary.autoFill.selectShip")}</Text>
</TouchableOpacity>
<Modal
visible={isOpen}
transparent
animationType="fade"
onRequestClose={() => setIsOpen(false)}
>
<TouchableOpacity
style={styles.modalOverlay}
activeOpacity={1}
onPress={() => setIsOpen(false)}
>
<View
style={[styles.modalContent, themedStyles.modalContent]}
onStartShouldSetResponder={() => true}
>
{/* Header */}
<View style={styles.modalHeader}>
<Text style={[styles.modalTitle, { color: colors.text }]}>
{t("diary.autoFill.modalTitle")}
</Text>
</View>
{/* Search Input */}
<View
style={[styles.searchContainer, themedStyles.searchContainer]}
>
<Ionicons
name="search"
size={20}
color={colors.textSecondary}
style={styles.searchIcon}
/>
<TextInput
style={[styles.searchInput, themedStyles.searchInput]}
placeholder={t("diary.searchShip")}
placeholderTextColor={colors.textSecondary}
value={searchText}
onChangeText={setSearchText}
autoCapitalize="none"
/>
{searchText.length > 0 && (
<TouchableOpacity onPress={() => setSearchText("")}>
<Ionicons
name="close-circle"
size={20}
color={colors.textSecondary}
/>
</TouchableOpacity>
)}
</View>
{isLoading ? (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color={colors.primary} />
<Text style={[styles.loadingText, { color: colors.textSecondary }]}>
{t("diary.autoFill.loading")}
</Text>
</View>
) : (
<ScrollView style={styles.optionsList}>
{/* Filtered ship options */}
{filteredShips.length > 0 ? (
filteredShips.map((ship) => (
<TouchableOpacity
key={ship.thingId}
style={[styles.option, themedStyles.option]}
onPress={() => handleSelectShip(ship.thingId)}
>
<View style={styles.optionContent}>
<Ionicons
name="boat"
size={20}
color={colors.primary}
style={styles.optionIcon}
/>
<Text style={[styles.optionText, themedStyles.optionText]}>
{ship.shipName}
</Text>
</View>
<Ionicons
name="chevron-forward"
size={20}
color={colors.textSecondary}
/>
</TouchableOpacity>
))
) : (
<View style={styles.emptyContainer}>
<Text style={[styles.emptyText, themedStyles.emptyText]}>
{t("diary.noShipsFound")}
</Text>
</View>
)}
</ScrollView>
)}
</View>
</TouchableOpacity>
</Modal>
</View>
);
}
const styles = StyleSheet.create({
container: {
marginBottom: 20,
padding: 16,
borderRadius: 12,
borderWidth: 1,
borderStyle: "dashed",
},
contentWrapper: {
flexDirection: "row",
alignItems: "center",
marginBottom: 12,
},
iconContainer: {
width: 40,
height: 40,
borderRadius: 20,
backgroundColor: "rgba(59, 130, 246, 0.1)",
justifyContent: "center",
alignItems: "center",
marginRight: 12,
},
textContainer: {
flex: 1,
},
label: {
fontSize: 16,
fontWeight: "600",
marginBottom: 4,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
description: {
fontSize: 13,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
button: {
paddingVertical: 10,
paddingHorizontal: 16,
borderRadius: 8,
alignItems: "center",
},
buttonText: {
fontSize: 14,
fontWeight: "600",
color: "#FFFFFF",
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
modalOverlay: {
flex: 1,
backgroundColor: "rgba(0, 0, 0, 0.5)",
justifyContent: "center",
alignItems: "center",
},
modalContent: {
borderRadius: 12,
width: "85%",
maxHeight: "70%",
overflow: "hidden",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 4,
},
shadowOpacity: 0.3,
shadowRadius: 8,
elevation: 8,
},
modalHeader: {
paddingHorizontal: 20,
paddingVertical: 16,
},
modalTitle: {
fontSize: 18,
fontWeight: "700",
textAlign: "center",
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
searchContainer: {
flexDirection: "row",
alignItems: "center",
paddingHorizontal: 16,
paddingVertical: 12,
borderBottomWidth: 1,
},
searchIcon: {
marginRight: 8,
},
searchInput: {
flex: 1,
fontSize: 16,
padding: 0,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
optionsList: {
maxHeight: 350,
},
option: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingHorizontal: 20,
paddingVertical: 16,
borderBottomWidth: 1,
},
optionContent: {
flexDirection: "row",
alignItems: "center",
flex: 1,
},
optionIcon: {
marginRight: 12,
},
optionText: {
fontSize: 16,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
emptyContainer: {
paddingVertical: 24,
alignItems: "center",
},
emptyText: {
fontSize: 14,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
loadingContainer: {
paddingVertical: 40,
alignItems: "center",
},
loadingText: {
marginTop: 12,
fontSize: 14,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
});

View File

@@ -0,0 +1,92 @@
import React from "react";
import {
View,
Text,
TextInput,
StyleSheet,
Platform,
} from "react-native";
import { useI18n } from "@/hooks/use-i18n";
import { useThemeContext } from "@/hooks/use-theme-context";
interface BasicInfoInputProps {
fishingGroundCodes: string;
onChange: (value: string) => void;
disabled?: boolean;
}
export default function BasicInfoInput({
fishingGroundCodes,
onChange,
disabled = false,
}: BasicInfoInputProps) {
const { t } = useI18n();
const { colors } = useThemeContext();
const themedStyles = {
label: { color: colors.text },
subLabel: { color: colors.textSecondary },
input: {
backgroundColor: disabled ? colors.backgroundSecondary : colors.card,
borderColor: colors.border,
color: colors.text,
},
};
return (
<View style={styles.container}>
<Text style={[styles.label, themedStyles.label]}>
{t("diary.fishingGroundCodes")}
</Text>
<Text style={[styles.subLabel, themedStyles.subLabel]}>
{t("diary.fishingGroundCodesHint")}
</Text>
<TextInput
style={[styles.input, themedStyles.input]}
value={fishingGroundCodes}
onChangeText={onChange}
placeholder={t("diary.fishingGroundCodesPlaceholder")}
placeholderTextColor={colors.textSecondary}
keyboardType="numeric"
editable={!disabled}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
marginBottom: 20,
},
label: {
fontSize: 16,
fontWeight: "600",
marginBottom: 12,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
subLabel: {
fontSize: 14,
marginBottom: 8,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
input: {
borderWidth: 1,
borderRadius: 8,
paddingHorizontal: 16,
paddingVertical: 12,
fontSize: 16,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
});

View File

@@ -0,0 +1,233 @@
import React from "react";
import {
View,
Text,
TouchableOpacity,
StyleSheet,
Platform,
TextInput,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useI18n } from "@/hooks/use-i18n";
import { useThemeContext } from "@/hooks/use-theme-context";
interface FishingGear {
id: string;
name: string;
number: string;
}
interface FishingGearListProps {
items: FishingGear[];
onChange: (items: FishingGear[]) => void;
disabled?: boolean;
}
export default function FishingGearList({
items,
onChange,
disabled = false,
}: FishingGearListProps) {
const { t } = useI18n();
const { colors } = useThemeContext();
const handleAddGear = () => {
const newGear: FishingGear = {
id: Date.now().toString(),
name: "",
number: "",
};
onChange([...items, newGear]);
};
const handleRemoveGear = (id: string) => {
onChange(items.filter((item) => item.id !== id));
};
const handleDuplicateGear = (gear: FishingGear) => {
const duplicatedGear: FishingGear = {
id: Date.now().toString(),
name: gear.name,
number: gear.number,
};
onChange([...items, duplicatedGear]);
};
const handleUpdateGear = (id: string, field: keyof FishingGear, value: string) => {
onChange(
items.map((item) =>
item.id === id ? { ...item, [field]: value } : item
)
);
};
const themedStyles = {
sectionTitle: { color: colors.text },
fieldLabel: { color: colors.text },
input: {
backgroundColor: colors.card,
borderColor: colors.border,
color: colors.text,
},
addButton: {
borderColor: colors.primary,
},
addButtonText: { color: colors.primary },
};
return (
<View style={styles.container}>
<Text style={[styles.sectionTitle, themedStyles.sectionTitle]}>
{t("diary.fishingGearList")}
</Text>
{/* Gear Items List */}
{items.map((gear, index) => (
<View key={gear.id} style={styles.gearRow}>
{/* Name Input */}
<View style={styles.inputGroup}>
<Text style={[styles.fieldLabel, themedStyles.fieldLabel]}>
{t("diary.gearName")}
</Text>
<TextInput
style={[styles.input, styles.nameInput, themedStyles.input]}
value={gear.name}
onChangeText={(value) => handleUpdateGear(gear.id, "name", value)}
placeholder={t("diary.gearNamePlaceholder")}
placeholderTextColor={colors.textSecondary}
editable={!disabled}
/>
</View>
{/* Number Input */}
<View style={styles.inputGroup}>
<Text style={[styles.fieldLabel, themedStyles.fieldLabel]}>
{t("diary.gearNumber")}
</Text>
<TextInput
style={[styles.input, styles.numberInput, themedStyles.input]}
value={gear.number}
onChangeText={(value) => handleUpdateGear(gear.id, "number", value)}
placeholder={t("diary.gearNumberPlaceholder")}
placeholderTextColor={colors.textSecondary}
keyboardType="numeric"
editable={!disabled}
/>
</View>
{/* Action Buttons - hide when disabled */}
{!disabled && (
<View style={styles.actionButtons}>
<TouchableOpacity
onPress={() => handleDuplicateGear(gear)}
hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
>
<Ionicons name="copy-outline" size={20} color={colors.text} />
</TouchableOpacity>
<TouchableOpacity
onPress={() => handleRemoveGear(gear.id)}
hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
>
<Ionicons name="trash-outline" size={20} color={colors.error} />
</TouchableOpacity>
</View>
)}
</View>
))}
{/* Add Button - hide when disabled */}
{!disabled && (
<TouchableOpacity
style={[styles.addButton, themedStyles.addButton]}
onPress={handleAddGear}
activeOpacity={0.7}
>
<Ionicons name="add" size={20} color={colors.primary} />
<Text style={[styles.addButtonText, themedStyles.addButtonText]}>
{t("diary.addFishingGear")}
</Text>
</TouchableOpacity>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
marginBottom: 20,
},
sectionTitle: {
fontSize: 16,
fontWeight: "700",
marginBottom: 16,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
gearRow: {
flexDirection: "row",
alignItems: "flex-end",
gap: 12,
marginBottom: 16,
},
inputGroup: {
flex: 1,
},
fieldLabel: {
fontSize: 14,
fontWeight: "500",
marginBottom: 6,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
input: {
borderWidth: 1,
borderRadius: 8,
paddingHorizontal: 12,
paddingVertical: 10,
fontSize: 15,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
nameInput: {
flex: 1,
},
numberInput: {
flex: 1,
},
actionButtons: {
flexDirection: "row",
gap: 12,
alignItems: "center",
paddingBottom: 10,
},
addButton: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: 8,
paddingVertical: 12,
paddingHorizontal: 16,
borderWidth: 1.5,
borderRadius: 8,
borderStyle: "dashed",
marginTop: 4,
},
addButtonText: {
fontSize: 14,
fontWeight: "600",
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
});

View File

@@ -0,0 +1,484 @@
import React, { useState } from "react";
import {
View,
Text,
TouchableOpacity,
StyleSheet,
Platform,
TextInput,
Modal,
ScrollView,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useI18n } from "@/hooks/use-i18n";
import { useThemeContext } from "@/hooks/use-theme-context";
interface TripCost {
id: string;
type: string;
amount: number;
unit: string;
cost_per_unit: number;
total_cost: number;
}
interface MaterialCostListProps {
items: TripCost[];
onChange: (items: TripCost[]) => void;
disabled?: boolean;
}
// Predefined cost types
const COST_TYPES = [
{ value: "fuel", label: "Nhiên liệu" },
{ value: "food", label: "Thực phẩm" },
{ value: "crew_salary", label: "Lương thuyền viên" },
{ value: "ice_salt_cost", label: "Muối đá" },
{ value: "other", label: "Khác" },
];
export default function MaterialCostList({
items,
onChange,
disabled = false,
}: MaterialCostListProps) {
const { t } = useI18n();
const { colors } = useThemeContext();
const [typeDropdownVisible, setTypeDropdownVisible] = useState<string | null>(null);
const handleAddMaterial = () => {
const newMaterial: TripCost = {
id: Date.now().toString(),
type: "",
amount: 0,
unit: "",
cost_per_unit: 0,
total_cost: 0,
};
onChange([...items, newMaterial]);
};
const handleRemoveMaterial = (id: string) => {
onChange(items.filter((item) => item.id !== id));
};
const handleDuplicateMaterial = (material: TripCost) => {
const duplicatedMaterial: TripCost = {
id: Date.now().toString(),
type: material.type,
amount: material.amount,
unit: material.unit,
cost_per_unit: material.cost_per_unit,
total_cost: material.total_cost,
};
onChange([...items, duplicatedMaterial]);
};
const handleUpdateMaterial = (id: string, field: keyof TripCost, value: string | number) => {
onChange(
items.map((item) => {
if (item.id === id) {
const updatedItem = { ...item, [field]: value };
// Auto-calculate total_cost when amount or cost_per_unit changes
if (field === "amount" || field === "cost_per_unit") {
const amount = field === "amount" ? Number(value) : item.amount;
const costPerUnit = field === "cost_per_unit" ? Number(value) : item.cost_per_unit;
updatedItem.total_cost = amount * costPerUnit;
}
return updatedItem;
}
return item;
})
);
};
const getTypeLabel = (value: string) => {
const type = COST_TYPES.find((t) => t.value === value);
return type ? type.label : value || t("diary.selectType");
};
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat("vi-VN").format(amount);
};
const themedStyles = {
sectionTitle: { color: colors.text },
fieldLabel: { color: colors.text },
input: {
backgroundColor: colors.card,
borderColor: colors.border,
color: colors.text,
},
dropdown: {
backgroundColor: colors.card,
borderColor: colors.border,
},
dropdownText: { color: colors.text },
placeholder: { color: colors.textSecondary },
addButton: {
borderColor: colors.primary,
},
addButtonText: { color: colors.primary },
modalOverlay: {
backgroundColor: "rgba(0, 0, 0, 0.5)",
},
modalContent: {
backgroundColor: colors.card,
},
option: {
borderBottomColor: colors.separator,
},
optionText: { color: colors.text },
};
return (
<View style={styles.container}>
<Text style={[styles.sectionTitle, themedStyles.sectionTitle]}>
{t("diary.materialCostList")}
</Text>
{/* Cost Items List */}
{items.map((cost) => (
<View key={cost.id} style={styles.costRow}>
<View style={styles.formRow}>
{/* Type Dropdown */}
<View style={[styles.inputGroup, styles.typeGroup]}>
<Text style={[styles.fieldLabel, themedStyles.fieldLabel]}>
{t("diary.costType")}
</Text>
<TouchableOpacity
style={[styles.dropdown, themedStyles.dropdown]}
onPress={disabled ? undefined : () => setTypeDropdownVisible(cost.id)}
activeOpacity={disabled ? 1 : 0.7}
disabled={disabled}
>
<Text
style={[
styles.dropdownText,
themedStyles.dropdownText,
!cost.type && themedStyles.placeholder,
]}
>
{getTypeLabel(cost.type)}
</Text>
{!disabled && (
<Ionicons
name="chevron-down"
size={16}
color={colors.textSecondary}
/>
)}
</TouchableOpacity>
{/* Type Dropdown Modal */}
<Modal
visible={typeDropdownVisible === cost.id}
transparent
animationType="fade"
onRequestClose={() => setTypeDropdownVisible(null)}
>
<TouchableOpacity
style={[styles.modalOverlay, themedStyles.modalOverlay]}
activeOpacity={1}
onPress={() => setTypeDropdownVisible(null)}
>
<View style={[styles.modalContent, themedStyles.modalContent]}>
<ScrollView>
{COST_TYPES.map((type) => (
<TouchableOpacity
key={type.value}
style={[styles.option, themedStyles.option]}
onPress={() => {
handleUpdateMaterial(cost.id, "type", type.value);
setTypeDropdownVisible(null);
}}
>
<Text
style={[styles.optionText, themedStyles.optionText]}
>
{type.label}
</Text>
{cost.type === type.value && (
<Ionicons
name="checkmark"
size={20}
color={colors.primary}
/>
)}
</TouchableOpacity>
))}
</ScrollView>
</View>
</TouchableOpacity>
</Modal>
</View>
{/* Amount Input */}
<View style={[styles.inputGroup, styles.smallGroup]}>
<Text style={[styles.fieldLabel, themedStyles.fieldLabel]}>
{t("diary.amount")}
</Text>
<TextInput
style={[styles.input, styles.smallInput, themedStyles.input]}
value={cost.amount.toString()}
onChangeText={(value) =>
handleUpdateMaterial(cost.id, "amount", Number(value) || 0)
}
placeholder="0"
placeholderTextColor={colors.textSecondary}
keyboardType="numeric"
editable={!disabled}
/>
</View>
{/* Unit Input */}
<View style={[styles.inputGroup, styles.smallGroup]}>
<Text style={[styles.fieldLabel, themedStyles.fieldLabel]}>
{t("diary.unit")}
</Text>
<TextInput
style={[styles.input, styles.smallInput, themedStyles.input]}
value={cost.unit}
onChangeText={(value) =>
handleUpdateMaterial(cost.id, "unit", value)
}
placeholder={t("diary.unitPlaceholder")}
placeholderTextColor={colors.textSecondary}
editable={!disabled}
/>
</View>
</View>
<View style={styles.formRow}>
{/* Cost Per Unit Input */}
<View style={[styles.inputGroup, styles.mediumGroup]}>
<Text style={[styles.fieldLabel, themedStyles.fieldLabel]}>
{t("diary.costPerUnit")}
</Text>
<TextInput
style={[styles.input, styles.mediumInput, themedStyles.input]}
value={cost.cost_per_unit.toString()}
onChangeText={(value) =>
handleUpdateMaterial(
cost.id,
"cost_per_unit",
Number(value) || 0
)
}
placeholder="0"
placeholderTextColor={colors.textSecondary}
keyboardType="numeric"
editable={!disabled}
/>
</View>
{/* Total Cost (Read-only, auto-calculated) */}
<View style={[styles.inputGroup, styles.mediumGroup]}>
<Text style={[styles.fieldLabel, themedStyles.fieldLabel]}>
{t("diary.totalCost")}
</Text>
<View style={[styles.input, styles.mediumInput, themedStyles.input, styles.readOnlyInput]}>
<Text style={[styles.readOnlyText, themedStyles.dropdownText]}>
{formatCurrency(cost.total_cost)}
</Text>
</View>
</View>
{/* Action Buttons - hide when disabled */}
{!disabled && (
<View style={styles.actionButtons}>
<TouchableOpacity
onPress={() => handleDuplicateMaterial(cost)}
hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
>
<Ionicons name="copy-outline" size={20} color={colors.text} />
</TouchableOpacity>
<TouchableOpacity
onPress={() => handleRemoveMaterial(cost.id)}
hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
>
<Ionicons
name="trash-outline"
size={20}
color={colors.error}
/>
</TouchableOpacity>
</View>
)}
</View>
</View>
))}
{/* Add Button - hide when disabled */}
{!disabled && (
<TouchableOpacity
style={[styles.addButton, themedStyles.addButton]}
onPress={handleAddMaterial}
activeOpacity={0.7}
>
<Ionicons name="add" size={20} color={colors.primary} />
<Text style={[styles.addButtonText, themedStyles.addButtonText]}>
{t("diary.addMaterialCost")}
</Text>
</TouchableOpacity>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
marginBottom: 20,
},
sectionTitle: {
fontSize: 16,
fontWeight: "700",
marginBottom: 16,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
costRow: {
marginBottom: 20,
paddingBottom: 16,
borderBottomWidth: 1,
borderBottomColor: "#E5E5E5",
},
formRow: {
flexDirection: "row",
alignItems: "flex-end",
gap: 12,
marginBottom: 12,
},
inputGroup: {
flex: 1,
},
typeGroup: {
flex: 1.5,
},
smallGroup: {
flex: 0.8,
},
mediumGroup: {
flex: 1,
},
fieldLabel: {
fontSize: 14,
fontWeight: "500",
marginBottom: 6,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
input: {
borderWidth: 1,
borderRadius: 8,
paddingHorizontal: 12,
paddingVertical: 10,
fontSize: 15,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
smallInput: {},
mediumInput: {},
dropdown: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
borderWidth: 1,
borderRadius: 8,
paddingHorizontal: 12,
paddingVertical: 10,
},
dropdownText: {
fontSize: 15,
flex: 1,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
readOnlyInput: {
justifyContent: "center",
opacity: 0.7,
},
readOnlyText: {
fontSize: 15,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
actionButtons: {
flexDirection: "row",
gap: 12,
alignItems: "center",
paddingBottom: 10,
},
addButton: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: 8,
paddingVertical: 12,
paddingHorizontal: 16,
borderWidth: 1.5,
borderRadius: 8,
borderStyle: "dashed",
marginTop: 4,
},
addButtonText: {
fontSize: 14,
fontWeight: "600",
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
// Modal styles
modalOverlay: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
modalContent: {
borderRadius: 12,
width: "80%",
maxHeight: "50%",
overflow: "hidden",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 4,
},
shadowOpacity: 0.3,
shadowRadius: 8,
elevation: 8,
},
option: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingHorizontal: 20,
paddingVertical: 16,
borderBottomWidth: 1,
},
optionText: {
fontSize: 16,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
});

View File

@@ -0,0 +1,179 @@
import React from "react";
import {
View,
Text,
TouchableOpacity,
StyleSheet,
Platform,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useI18n } from "@/hooks/use-i18n";
import { useThemeContext } from "@/hooks/use-theme-context";
interface PortSelectorProps {
departurePortId: number;
arrivalPortId: number;
onDeparturePortChange: (portId: number) => void;
onArrivalPortChange: (portId: number) => void;
disabled?: boolean;
}
export default function PortSelector({
departurePortId,
arrivalPortId,
onDeparturePortChange,
onArrivalPortChange,
disabled = false,
}: PortSelectorProps) {
const { t } = useI18n();
const { colors } = useThemeContext();
const handleSelectDeparturePort = () => {
console.log("Select departure port pressed");
// TODO: Implement port selection modal/dropdown
// For now, just set a dummy ID
onDeparturePortChange(1);
};
const handleSelectArrivalPort = () => {
console.log("Select arrival port pressed");
// TODO: Implement port selection modal/dropdown
// For now, just set a dummy ID
onArrivalPortChange(1);
};
// Helper to display port name (in production, fetch from port list by ID)
const getPortDisplayName = (portId: number): string => {
// TODO: Fetch actual port name by ID from port list
return portId ? `Cảng (ID: ${portId})` : t("diary.selectPort");
};
const themedStyles = {
label: { color: colors.text },
portSelector: {
backgroundColor: colors.card,
borderColor: colors.border,
},
portText: { color: colors.text },
placeholder: { color: colors.textSecondary },
};
return (
<View style={styles.container}>
<Text style={[styles.label, themedStyles.label]}>
{t("diary.portLabel")}
</Text>
<View style={styles.portContainer}>
{/* Departure Port */}
<View style={styles.portSection}>
<Text style={[styles.subLabel, themedStyles.placeholder]}>
{t("diary.departurePort")}
</Text>
<TouchableOpacity
style={[styles.portSelector, themedStyles.portSelector]}
onPress={disabled ? undefined : handleSelectDeparturePort}
activeOpacity={disabled ? 1 : 0.7}
disabled={disabled}
>
<Text
style={[
styles.portText,
themedStyles.portText,
!departurePortId && themedStyles.placeholder,
]}
>
{getPortDisplayName(departurePortId)}
</Text>
{!disabled && (
<Ionicons
name="ellipsis-horizontal"
size={20}
color={colors.textSecondary}
/>
)}
</TouchableOpacity>
</View>
{/* Arrival Port */}
<View style={styles.portSection}>
<Text style={[styles.subLabel, themedStyles.placeholder]}>
{t("diary.arrivalPort")}
</Text>
<TouchableOpacity
style={[styles.portSelector, themedStyles.portSelector]}
onPress={disabled ? undefined : handleSelectArrivalPort}
activeOpacity={disabled ? 1 : 0.7}
disabled={disabled}
>
<Text
style={[
styles.portText,
themedStyles.portText,
!arrivalPortId && themedStyles.placeholder,
]}
>
{getPortDisplayName(arrivalPortId)}
</Text>
{!disabled && (
<Ionicons
name="ellipsis-horizontal"
size={20}
color={colors.textSecondary}
/>
)}
</TouchableOpacity>
</View>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
marginBottom: 20,
},
label: {
fontSize: 16,
fontWeight: "600",
marginBottom: 12,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
subLabel: {
fontSize: 14,
marginBottom: 6,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
portContainer: {
flexDirection: "row",
gap: 12,
},
portSection: {
flex: 1,
},
portSelector: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
borderWidth: 1,
borderRadius: 8,
paddingHorizontal: 12,
paddingVertical: 12,
},
portText: {
fontSize: 15,
flex: 1,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
});

View File

@@ -0,0 +1,301 @@
import React, { useState } from "react";
import {
View,
Text,
TouchableOpacity,
StyleSheet,
Modal,
Platform,
ScrollView,
TextInput,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useThings } from "@/state/use-thing";
import { useI18n } from "@/hooks/use-i18n";
import { useThemeContext } from "@/hooks/use-theme-context";
interface ShipSelectorProps {
selectedShipId: string;
onChange: (shipId: string) => void;
disabled?: boolean;
}
export default function ShipSelector({
selectedShipId,
onChange,
disabled = false,
}: ShipSelectorProps) {
const { t } = useI18n();
const { colors } = useThemeContext();
const [isOpen, setIsOpen] = useState(false);
const [searchText, setSearchText] = useState("");
const { things } = useThings();
// Convert things to ship options
const shipOptions =
things
?.filter((thing) => thing.id != null)
.map((thing) => ({
id: thing.id as string,
shipName: thing.metadata?.ship_name || "",
})) || [];
// Filter ships based on search text
const filteredShips = shipOptions.filter((ship) => {
const searchLower = searchText.toLowerCase();
return ship.shipName.toLowerCase().includes(searchLower);
});
const handleSelect = (shipId: string) => {
onChange(shipId);
setIsOpen(false);
setSearchText("");
};
const selectedShip = shipOptions.find((ship) => ship.id === selectedShipId);
const displayValue = selectedShip
? selectedShip.shipName
: t("diary.selectShip");
const themedStyles = {
label: { color: colors.text },
selector: {
backgroundColor: disabled ? colors.backgroundSecondary : colors.card,
borderColor: colors.border,
},
selectorText: { color: colors.text },
placeholder: { color: colors.textSecondary },
modalContent: { backgroundColor: colors.card },
searchContainer: {
backgroundColor: colors.backgroundSecondary,
borderColor: colors.border,
},
searchInput: { color: colors.text },
option: { borderBottomColor: colors.separator },
selectedOption: { backgroundColor: colors.backgroundSecondary },
optionText: { color: colors.text },
emptyText: { color: colors.textSecondary },
};
return (
<View style={styles.container}>
<Text style={[styles.label, themedStyles.label]}>
{t("diary.shipSelector")}
<Text style={styles.required}> *</Text>
</Text>
<TouchableOpacity
style={[styles.selector, themedStyles.selector]}
onPress={() => !disabled && setIsOpen(true)}
activeOpacity={disabled ? 1 : 0.7}
disabled={disabled}
>
<Text
style={[
styles.selectorText,
themedStyles.selectorText,
!selectedShipId && themedStyles.placeholder,
]}
>
{displayValue}
</Text>
{!disabled && (
<Ionicons
name="ellipsis-horizontal"
size={20}
color={colors.textSecondary}
/>
)}
</TouchableOpacity>
<Modal
visible={isOpen}
transparent
animationType="fade"
onRequestClose={() => setIsOpen(false)}
>
<TouchableOpacity
style={styles.modalOverlay}
activeOpacity={1}
onPress={() => setIsOpen(false)}
>
<View
style={[styles.modalContent, themedStyles.modalContent]}
onStartShouldSetResponder={() => true}
>
{/* Search Input */}
<View
style={[styles.searchContainer, themedStyles.searchContainer]}
>
<Ionicons
name="search"
size={20}
color={colors.textSecondary}
style={styles.searchIcon}
/>
<TextInput
style={[styles.searchInput, themedStyles.searchInput]}
placeholder={t("diary.searchShip")}
placeholderTextColor={colors.textSecondary}
value={searchText}
onChangeText={setSearchText}
autoCapitalize="none"
/>
{searchText.length > 0 && (
<TouchableOpacity onPress={() => setSearchText("")}>
<Ionicons
name="close-circle"
size={20}
color={colors.textSecondary}
/>
</TouchableOpacity>
)}
</View>
<ScrollView style={styles.optionsList}>
{/* Filtered ship options */}
{filteredShips.length > 0 ? (
filteredShips.map((ship) => (
<TouchableOpacity
key={ship.id}
style={[
styles.option,
themedStyles.option,
selectedShipId === ship.id && themedStyles.selectedOption,
]}
onPress={() => handleSelect(ship.id)}
>
<Text style={[styles.optionText, themedStyles.optionText]}>
{ship.shipName}
</Text>
{selectedShipId === ship.id && (
<Ionicons
name="checkmark"
size={20}
color={colors.primary}
/>
)}
</TouchableOpacity>
))
) : (
<View style={styles.emptyContainer}>
<Text style={[styles.emptyText, themedStyles.emptyText]}>
{t("diary.noShipsFound")}
</Text>
</View>
)}
</ScrollView>
</View>
</TouchableOpacity>
</Modal>
</View>
);
}
const styles = StyleSheet.create({
container: {
marginBottom: 20,
},
label: {
fontSize: 16,
fontWeight: "600",
marginBottom: 8,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
required: {
color: "#EF4444",
},
selector: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
borderWidth: 1,
borderRadius: 8,
paddingHorizontal: 16,
paddingVertical: 12,
},
selectorText: {
fontSize: 16,
flex: 1,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
modalOverlay: {
flex: 1,
backgroundColor: "rgba(0, 0, 0, 0.5)",
justifyContent: "center",
alignItems: "center",
},
modalContent: {
borderRadius: 12,
width: "85%",
maxHeight: "70%",
overflow: "hidden",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 4,
},
shadowOpacity: 0.3,
shadowRadius: 8,
elevation: 8,
},
searchContainer: {
flexDirection: "row",
alignItems: "center",
paddingHorizontal: 16,
paddingVertical: 12,
borderBottomWidth: 1,
},
searchIcon: {
marginRight: 8,
},
searchInput: {
flex: 1,
fontSize: 16,
padding: 0,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
optionsList: {
maxHeight: 350,
},
option: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingHorizontal: 20,
paddingVertical: 16,
borderBottomWidth: 1,
},
optionText: {
fontSize: 16,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
emptyContainer: {
paddingVertical: 24,
alignItems: "center",
},
emptyText: {
fontSize: 14,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
});

View File

@@ -0,0 +1,345 @@
import React, { useState } from "react";
import {
View,
Text,
TouchableOpacity,
StyleSheet,
Platform,
Modal,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import DateTimePicker from "@react-native-community/datetimepicker";
import { useI18n } from "@/hooks/use-i18n";
import { useThemeContext } from "@/hooks/use-theme-context";
interface TripDurationPickerProps {
startDate: Date | null;
endDate: Date | null;
onStartDateChange: (date: Date | null) => void;
onEndDateChange: (date: Date | null) => void;
disabled?: boolean;
}
export default function TripDurationPicker({
startDate,
endDate,
onStartDateChange,
onEndDateChange,
disabled = false,
}: TripDurationPickerProps) {
const { t } = useI18n();
const { colors, colorScheme } = useThemeContext();
const [showStartPicker, setShowStartPicker] = useState(false);
const [showEndPicker, setShowEndPicker] = useState(false);
// Temp states to hold the picker value before confirming
const [tempStartDate, setTempStartDate] = useState<Date>(new Date());
const [tempEndDate, setTempEndDate] = useState<Date>(new Date());
const formatDate = (date: Date | null) => {
if (!date) return "";
const day = date.getDate().toString().padStart(2, "0");
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const year = date.getFullYear();
return `${day}/${month}/${year}`;
};
const handleOpenStartPicker = () => {
const today = new Date();
const dateToUse = startDate || today;
// If no date selected, immediately set to today
if (!startDate) {
onStartDateChange(today);
}
// Always set tempStartDate to the date we're using (today if no date was selected)
setTempStartDate(dateToUse);
setShowStartPicker(true);
};
const handleOpenEndPicker = () => {
const today = new Date();
const dateToUse = endDate || today;
// If no date selected, immediately set to today
if (!endDate) {
onEndDateChange(today);
}
// Always set tempEndDate to the date we're using (today if no date was selected)
setTempEndDate(dateToUse);
setShowEndPicker(true);
};
const handleStartDateChange = (event: any, selectedDate?: Date) => {
if (Platform.OS === "android") {
setShowStartPicker(false);
if (event.type === "set" && selectedDate) {
onStartDateChange(selectedDate);
}
} else if (selectedDate) {
// For iOS, update both temp and actual date immediately
setTempStartDate(selectedDate);
onStartDateChange(selectedDate);
}
};
const handleEndDateChange = (event: any, selectedDate?: Date) => {
if (Platform.OS === "android") {
setShowEndPicker(false);
if (event.type === "set" && selectedDate) {
onEndDateChange(selectedDate);
}
} else if (selectedDate) {
// For iOS, update both temp and actual date immediately
setTempEndDate(selectedDate);
onEndDateChange(selectedDate);
}
};
const handleConfirmStartDate = () => {
setShowStartPicker(false);
};
const handleConfirmEndDate = () => {
setShowEndPicker(false);
};
const themedStyles = {
label: { color: colors.text },
dateInput: {
backgroundColor: colors.card,
borderColor: colors.border,
},
dateText: { color: colors.text },
placeholder: { color: colors.textSecondary },
pickerContainer: { backgroundColor: colors.card },
pickerHeader: { borderBottomColor: colors.border },
pickerTitle: { color: colors.text },
cancelButton: { color: colors.textSecondary },
};
return (
<View style={styles.container}>
<Text style={[styles.label, themedStyles.label]}>
{t("diary.tripDuration")}
</Text>
<View style={styles.dateRangeContainer}>
{/* Start Date */}
<View style={styles.dateSection}>
<Text style={[styles.subLabel, themedStyles.placeholder]}>
{t("diary.startDate")}
</Text>
<TouchableOpacity
style={[styles.dateInput, themedStyles.dateInput]}
onPress={disabled ? undefined : handleOpenStartPicker}
activeOpacity={disabled ? 1 : 0.7}
disabled={disabled}
>
<Text
style={[
styles.dateText,
themedStyles.dateText,
!startDate && themedStyles.placeholder,
]}
>
{startDate ? formatDate(startDate) : t("diary.selectDate")}
</Text>
{!disabled && (
<Ionicons
name="calendar-outline"
size={20}
color={colors.textSecondary}
/>
)}
</TouchableOpacity>
</View>
{/* End Date */}
<View style={styles.dateSection}>
<Text style={[styles.subLabel, themedStyles.placeholder]}>
{t("diary.endDate")}
</Text>
<TouchableOpacity
style={[styles.dateInput, themedStyles.dateInput]}
onPress={disabled ? undefined : handleOpenEndPicker}
activeOpacity={disabled ? 1 : 0.7}
disabled={disabled}
>
<Text
style={[
styles.dateText,
themedStyles.dateText,
!endDate && themedStyles.placeholder,
]}
>
{endDate ? formatDate(endDate) : t("diary.selectDate")}
</Text>
{!disabled && (
<Ionicons
name="calendar-outline"
size={20}
color={colors.textSecondary}
/>
)}
</TouchableOpacity>
</View>
</View>
{/* Start Date Picker */}
{showStartPicker && (
<Modal transparent animationType="fade" visible={showStartPicker}>
<View style={styles.modalOverlay}>
<View style={[styles.pickerContainer, themedStyles.pickerContainer]}>
<View style={[styles.pickerHeader, themedStyles.pickerHeader]}>
<TouchableOpacity onPress={() => setShowStartPicker(false)}>
<Text style={[styles.cancelButton, themedStyles.cancelButton]}>
{t("common.cancel")}
</Text>
</TouchableOpacity>
<Text style={[styles.pickerTitle, themedStyles.pickerTitle]}>
{t("diary.selectStartDate")}
</Text>
<TouchableOpacity onPress={handleConfirmStartDate}>
<Text style={styles.doneButton}>{t("common.done")}</Text>
</TouchableOpacity>
</View>
<DateTimePicker
value={tempStartDate}
mode="date"
display={Platform.OS === "ios" ? "spinner" : "default"}
onChange={handleStartDateChange}
maximumDate={endDate || undefined}
themeVariant={colorScheme}
textColor={colors.text}
/>
</View>
</View>
</Modal>
)}
{/* End Date Picker */}
{showEndPicker && (
<Modal transparent animationType="fade" visible={showEndPicker}>
<View style={styles.modalOverlay}>
<View style={[styles.pickerContainer, themedStyles.pickerContainer]}>
<View style={[styles.pickerHeader, themedStyles.pickerHeader]}>
<TouchableOpacity onPress={() => setShowEndPicker(false)}>
<Text style={[styles.cancelButton, themedStyles.cancelButton]}>
{t("common.cancel")}
</Text>
</TouchableOpacity>
<Text style={[styles.pickerTitle, themedStyles.pickerTitle]}>
{t("diary.selectEndDate")}
</Text>
<TouchableOpacity onPress={handleConfirmEndDate}>
<Text style={styles.doneButton}>{t("common.done")}</Text>
</TouchableOpacity>
</View>
<DateTimePicker
value={tempEndDate}
mode="date"
display={Platform.OS === "ios" ? "spinner" : "default"}
onChange={handleEndDateChange}
minimumDate={startDate || undefined}
themeVariant={colorScheme}
textColor={colors.text}
/>
</View>
</View>
</Modal>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
marginBottom: 20,
},
label: {
fontSize: 16,
fontWeight: "600",
marginBottom: 12,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
subLabel: {
fontSize: 14,
marginBottom: 6,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
dateRangeContainer: {
flexDirection: "row",
gap: 12,
},
dateSection: {
flex: 1,
},
dateInput: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
borderWidth: 1,
borderRadius: 8,
paddingHorizontal: 12,
paddingVertical: 12,
},
dateText: {
fontSize: 15,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
modalOverlay: {
flex: 1,
backgroundColor: "rgba(0, 0, 0, 0.5)",
justifyContent: "flex-end",
},
pickerContainer: {
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
paddingBottom: 20,
},
pickerHeader: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingHorizontal: 20,
paddingVertical: 16,
borderBottomWidth: 1,
},
pickerTitle: {
fontSize: 16,
fontWeight: "600",
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
cancelButton: {
fontSize: 16,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
doneButton: {
fontSize: 16,
fontWeight: "600",
color: "#3B82F6",
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
});

View File

@@ -0,0 +1,74 @@
import React from "react";
import {
View,
Text,
TextInput,
StyleSheet,
Platform,
} from "react-native";
import { useI18n } from "@/hooks/use-i18n";
import { useThemeContext } from "@/hooks/use-theme-context";
interface TripNameInputProps {
value: string;
onChange: (value: string) => void;
disabled?: boolean;
}
export default function TripNameInput({ value, onChange, disabled = false }: TripNameInputProps) {
const { t } = useI18n();
const { colors } = useThemeContext();
const themedStyles = {
label: { color: colors.text },
input: {
backgroundColor: disabled ? colors.backgroundSecondary : colors.card,
borderColor: colors.border,
color: colors.text,
},
};
return (
<View style={styles.container}>
<Text style={[styles.label, themedStyles.label]}>
{t("diary.tripNameLabel")}
</Text>
<TextInput
style={[styles.input, themedStyles.input]}
value={value}
onChangeText={onChange}
placeholder={t("diary.tripNamePlaceholder")}
placeholderTextColor={colors.textSecondary}
editable={!disabled}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
marginBottom: 20,
},
label: {
fontSize: 16,
fontWeight: "600",
marginBottom: 8,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
input: {
borderWidth: 1,
borderRadius: 8,
paddingHorizontal: 16,
paddingVertical: 12,
fontSize: 16,
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
});

View File

@@ -0,0 +1,582 @@
import React, { useState, useEffect, useRef } from "react";
import {
View,
Text,
Modal,
TouchableOpacity,
StyleSheet,
Platform,
ScrollView,
Alert,
ActivityIndicator,
Animated,
Dimensions,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useI18n } from "@/hooks/use-i18n";
import { useThemeContext } from "@/hooks/use-theme-context";
import FishingGearList from "@/components/diary/TripFormModal/FishingGearList";
import MaterialCostList from "@/components/diary/TripFormModal/MaterialCostList";
import TripNameInput from "@/components/diary/TripFormModal/TripNameInput";
import TripDurationPicker from "@/components/diary/TripFormModal/TripDurationPicker";
import PortSelector from "@/components/diary/TripFormModal/PortSelector";
import BasicInfoInput from "@/components/diary/TripFormModal/BasicInfoInput";
import ShipSelector from "./ShipSelector";
import AutoFillSection from "./AutoFillSection";
import { createTrip, updateTrip } from "@/controller/TripController";
// Internal component interfaces - extend from Model with local id for state management
export interface FishingGear extends Model.FishingGear {
id: string;
}
export interface TripCost extends Model.TripCost {
id: string;
}
interface TripFormModalProps {
visible: boolean;
onClose: () => void;
onSuccess?: () => void;
mode?: 'add' | 'edit' | 'view';
tripData?: Model.Trip;
}
export default function TripFormModal({
visible,
onClose,
onSuccess,
mode = 'add',
tripData,
}: TripFormModalProps) {
const { t } = useI18n();
const { colors } = useThemeContext();
const isEditMode = mode === 'edit';
const isViewMode = mode === 'view';
const isReadOnly = isViewMode; // View mode is read-only
// Animation values
const fadeAnim = useRef(new Animated.Value(0)).current;
const slideAnim = useRef(new Animated.Value(Dimensions.get('window').height)).current;
// Handle animation when modal visibility changes
useEffect(() => {
if (visible) {
// Open animation: fade overlay + slide content up
Animated.parallel([
Animated.timing(fadeAnim, {
toValue: 1,
duration: 300,
useNativeDriver: true,
}),
Animated.timing(slideAnim, {
toValue: 0,
duration: 300,
useNativeDriver: true,
}),
]).start();
}
}, [visible, fadeAnim, slideAnim]);
// Form state
const [selectedShipId, setSelectedShipId] = useState<string>("");
const [tripName, setTripName] = useState("");
const [fishingGears, setFishingGears] = useState<FishingGear[]>([]);
const [tripCosts, setTripCosts] = useState<TripCost[]>([]);
const [startDate, setStartDate] = useState<Date | null>(null);
const [endDate, setEndDate] = useState<Date | null>(null);
const [departurePortId, setDeparturePortId] = useState<number>(1);
const [arrivalPortId, setArrivalPortId] = useState<number>(1);
const [fishingGroundCodes, setFishingGroundCodes] = useState<string>("");
const [isSubmitting, setIsSubmitting] = useState(false);
// Pre-fill form when in edit or view mode
useEffect(() => {
if ((isEditMode || isViewMode) && tripData && visible) {
// Fill ship ID (use vms_id as thingId)
setSelectedShipId(tripData.vms_id || "");
// Fill trip name
setTripName(tripData.name || "");
// Fill fishing gears
if (tripData.fishing_gears && Array.isArray(tripData.fishing_gears)) {
const gears: FishingGear[] = tripData.fishing_gears.map((gear, index) => ({
id: `${mode}-${Date.now()}-${index}`,
name: gear.name || "",
number: gear.number?.toString() || "",
}));
setFishingGears(gears);
}
// Fill trip costs
if (tripData.trip_cost && Array.isArray(tripData.trip_cost)) {
const costs: TripCost[] = tripData.trip_cost.map((cost, index) => ({
id: `${mode}-${Date.now()}-${index}`,
type: cost.type || "",
amount: cost.amount || 0,
unit: cost.unit || "",
cost_per_unit: cost.cost_per_unit || 0,
total_cost: cost.total_cost || 0,
}));
setTripCosts(costs);
}
// Fill dates
if (tripData.departure_time) {
setStartDate(new Date(tripData.departure_time));
}
if (tripData.arrival_time) {
setEndDate(new Date(tripData.arrival_time));
}
// Fill ports
if (tripData.departure_port_id) {
setDeparturePortId(tripData.departure_port_id);
}
if (tripData.arrival_port_id) {
setArrivalPortId(tripData.arrival_port_id);
}
// Fill fishing ground codes
if (tripData.fishing_ground_codes && Array.isArray(tripData.fishing_ground_codes)) {
setFishingGroundCodes(tripData.fishing_ground_codes.join(", "));
}
}
}, [isEditMode, isViewMode, tripData, visible, mode]);
const handleCancel = () => {
// Close animation: fade overlay + slide content down
Animated.parallel([
Animated.timing(fadeAnim, {
toValue: 0,
duration: 250,
useNativeDriver: true,
}),
Animated.timing(slideAnim, {
toValue: Dimensions.get('window').height,
duration: 250,
useNativeDriver: true,
}),
]).start(() => {
// Close modal after animation completes
onClose();
// Only reset form in add/edit mode, not needed for view mode
if (!isViewMode) {
// Reset form after closing
setTimeout(() => {
setSelectedShipId("");
setTripName("");
setFishingGears([]);
setTripCosts([]);
setStartDate(null);
setEndDate(null);
setDeparturePortId(1);
setArrivalPortId(1);
setFishingGroundCodes("");
}, 100);
}
});
};
// Handle close modal after successful submit - always resets form
const handleSuccessClose = () => {
// Reset animation values for next open
fadeAnim.setValue(0);
slideAnim.setValue(Dimensions.get('window').height);
// Close modal immediately
onClose();
// Reset form after closing
setTimeout(() => {
setSelectedShipId("");
setTripName("");
setFishingGears([]);
setTripCosts([]);
setStartDate(null);
setEndDate(null);
setDeparturePortId(1);
setArrivalPortId(1);
setFishingGroundCodes("");
}, 100);
};
// Handle auto-fill from last trip data
const handleAutoFill = (tripData: Model.Trip, selectedThingId: string) => {
// Fill ship ID (use the thingId from the selected ship for ShipSelector)
setSelectedShipId(selectedThingId);
// Fill trip name
// if (tripData.name) {
// setTripName(tripData.name);
// }
// Fill fishing gears
if (tripData.fishing_gears && Array.isArray(tripData.fishing_gears)) {
const gears: FishingGear[] = tripData.fishing_gears.map(
(gear, index) => ({
id: `auto-${Date.now()}-${index}`,
name: gear.name || "",
number: gear.number?.toString() || "",
})
);
setFishingGears(gears);
}
// Fill trip costs
if (tripData.trip_cost && Array.isArray(tripData.trip_cost)) {
const costs: TripCost[] = tripData.trip_cost.map((cost, index) => ({
id: `auto-${Date.now()}-${index}`,
type: cost.type || "",
amount: cost.amount || 0,
unit: cost.unit || "",
cost_per_unit: cost.cost_per_unit || 0,
total_cost: cost.total_cost || 0,
}));
setTripCosts(costs);
}
// Fill departure and arrival ports
if (tripData.departure_port_id) {
setDeparturePortId(tripData.departure_port_id);
}
if (tripData.arrival_port_id) {
setArrivalPortId(tripData.arrival_port_id);
}
// Fill fishing ground codes
if (
tripData.fishing_ground_codes &&
Array.isArray(tripData.fishing_ground_codes)
) {
setFishingGroundCodes(tripData.fishing_ground_codes.join(", "));
}
};
const handleSubmit = async () => {
// Validate thingId is required
if (!selectedShipId) {
Alert.alert(t("common.error"), t("diary.validation.shipRequired"));
return;
}
// Validate dates are required
if (!startDate || !endDate) {
Alert.alert(t("common.error"), t("diary.validation.datesRequired"));
return;
}
// Validate trip name is required
if (!tripName.trim()) {
Alert.alert(t("common.error"), t("diary.validation.tripNameRequired"));
return;
}
// Parse fishing ground codes from comma-separated string to array of numbers
const fishingGroundCodesArray = fishingGroundCodes
.split(",")
.map((code) => parseInt(code.trim()))
.filter((code) => !isNaN(code));
// Format API body
const apiBody: Model.TripAPIBody = {
thing_id: selectedShipId,
name: tripName,
departure_time: startDate ? startDate.toISOString() : "",
departure_port_id: departurePortId,
arrival_time: endDate ? endDate.toISOString() : "",
arrival_port_id: arrivalPortId,
fishing_ground_codes: fishingGroundCodesArray,
fishing_gears: fishingGears.map((gear) => ({
name: gear.name,
number: gear.number,
})),
trip_cost: tripCosts.map((cost) => ({
type: cost.type,
amount: cost.amount,
unit: cost.unit,
cost_per_unit: cost.cost_per_unit,
total_cost: cost.total_cost,
})),
};
setIsSubmitting(true);
try {
let response;
if (isEditMode && tripData) {
// Edit mode: call updateTrip
response = await updateTrip(tripData.id, apiBody);
} else {
// Add mode: call createTrip
response = await createTrip(selectedShipId, apiBody);
}
// Check if response is successful (response exists)
// Call onSuccess callback first (to refresh data)
if (onSuccess) {
onSuccess();
}
// Show success alert
Alert.alert(
t("common.success"),
isEditMode ? t("diary.updateTripSuccess") : t("diary.createTripSuccess")
);
// Reset form and close modal
console.log("Calling handleSuccessClose");
handleSuccessClose();
} catch (error: any) {
console.error(isEditMode ? "Error updating trip:" : "Error creating trip:", error);
// Log detailed error information for debugging
if (error.response) {
console.error("Response status:", error.response.status);
console.error("Response data:", JSON.stringify(error.response.data, null, 2));
}
console.log("Request body was:", JSON.stringify(apiBody, null, 2));
Alert.alert(
t("common.error"),
isEditMode ? t("diary.updateTripError") : t("diary.createTripError")
);
} finally {
setIsSubmitting(false);
}
};
const themedStyles = {
modalContainer: {
backgroundColor: colors.card,
},
header: {
borderBottomColor: colors.separator,
},
title: {
color: colors.text,
},
footer: {
borderTopColor: colors.separator,
},
cancelButton: {
backgroundColor: colors.backgroundSecondary,
},
cancelButtonText: {
color: colors.textSecondary,
},
submitButton: {
backgroundColor: colors.primary,
},
};
return (
<Modal
visible={visible}
animationType="none"
transparent
onRequestClose={handleCancel}
>
<Animated.View style={[styles.overlay, { opacity: fadeAnim }]}>
<Animated.View
style={[
styles.modalContainer,
themedStyles.modalContainer,
{ transform: [{ translateY: slideAnim }] }
]}
>
{/* Header */}
<View style={[styles.header, themedStyles.header]}>
<TouchableOpacity onPress={handleCancel} style={styles.closeButton}>
<Ionicons name="close" size={24} color={colors.text} />
</TouchableOpacity>
<Text style={[styles.title, themedStyles.title]}>
{isViewMode
? t("diary.viewTrip")
: isEditMode
? t("diary.editTrip")
: t("diary.addTrip")}
</Text>
<View style={styles.placeholder} />
</View>
{/* Content */}
<ScrollView
style={styles.content}
showsVerticalScrollIndicator={false}
contentContainerStyle={isViewMode ? { paddingBottom: 40 } : undefined}
>
{/* Auto Fill Section - only show in add mode */}
{!isEditMode && !isViewMode && <AutoFillSection onAutoFill={handleAutoFill} />}
{/* Ship Selector - disabled in edit and view mode */}
<ShipSelector
selectedShipId={selectedShipId}
onChange={setSelectedShipId}
disabled={isEditMode || isViewMode}
/>
{/* Trip Name */}
<TripNameInput value={tripName} onChange={setTripName} disabled={isReadOnly} />
{/* Fishing Gear List */}
<FishingGearList items={fishingGears} onChange={setFishingGears} disabled={isReadOnly} />
{/* Trip Cost List */}
<MaterialCostList items={tripCosts} onChange={setTripCosts} disabled={isReadOnly} />
{/* Trip Duration */}
<TripDurationPicker
startDate={startDate}
endDate={endDate}
onStartDateChange={setStartDate}
onEndDateChange={setEndDate}
disabled={isReadOnly}
/>
{/* Port Selector */}
<PortSelector
departurePortId={departurePortId}
arrivalPortId={arrivalPortId}
onDeparturePortChange={setDeparturePortId}
onArrivalPortChange={setArrivalPortId}
disabled={isReadOnly}
/>
{/* Fishing Ground Codes */}
<BasicInfoInput
fishingGroundCodes={fishingGroundCodes}
onChange={setFishingGroundCodes}
disabled={isReadOnly}
/>
</ScrollView>
{/* Footer - hide in view mode */}
{!isViewMode && (
<View style={[styles.footer, themedStyles.footer]}>
<TouchableOpacity
style={[styles.cancelButton, themedStyles.cancelButton]}
onPress={handleCancel}
activeOpacity={0.7}
>
<Text
style={[styles.cancelButtonText, themedStyles.cancelButtonText]}
>
{t("common.cancel")}
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[
styles.submitButton,
themedStyles.submitButton,
isSubmitting && styles.submitButtonDisabled
]}
onPress={handleSubmit}
activeOpacity={0.7}
disabled={isSubmitting}
>
{isSubmitting ? (
<ActivityIndicator size="small" color="#FFFFFF" />
) : (
<Text style={styles.submitButtonText}>
{isEditMode ? t("diary.saveChanges") : t("diary.createTrip")}
</Text>
)}
</TouchableOpacity>
</View>
)}
</Animated.View>
</Animated.View>
</Modal>
);
}
const styles = StyleSheet.create({
overlay: {
flex: 1,
backgroundColor: "rgba(0, 0, 0, 0.5)",
justifyContent: "flex-end",
},
modalContainer: {
borderTopLeftRadius: 24,
borderTopRightRadius: 24,
maxHeight: "90%",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: -4,
},
shadowOpacity: 0.1,
shadowRadius: 12,
elevation: 8,
},
header: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingHorizontal: 20,
paddingVertical: 16,
borderBottomWidth: 1,
},
closeButton: {
padding: 4,
},
title: {
fontSize: 18,
fontWeight: "700",
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
placeholder: {
width: 32,
},
content: {
padding: 20,
},
footer: {
flexDirection: "row",
gap: 12,
padding: 20,
borderTopWidth: 1,
},
cancelButton: {
flex: 1,
paddingVertical: 14,
borderRadius: 12,
alignItems: "center",
},
cancelButtonText: {
fontSize: 16,
fontWeight: "600",
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
submitButton: {
flex: 1,
paddingVertical: 14,
borderRadius: 12,
alignItems: "center",
},
submitButtonDisabled: {
opacity: 0.7,
},
submitButtonText: {
fontSize: 16,
fontWeight: "600",
color: "#FFFFFF",
fontFamily: Platform.select({
ios: "System",
android: "Roboto",
default: "System",
}),
},
});